www.webdeveloper.com
Results 1 to 3 of 3

Thread: defining default values for non-existent properties of an object...

  1. #1
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843

    defining default values for non-existent properties of an object...

    I have an application that uses callback functions that alter properties of an object, example
    Code:
    function app()
    {
        this.attributes = {
    		"a": 100,
    		"b": 100,
    		"c": 100,
    		"d": 100,
    		"e": 100,
    		"f": 100
    	};
    }
    my callback functions look like this
    Code:
    function()
    {
    	this.attributes["x"] = (this.attributes["x"] || 0) + 100;
    }
    I would like to write it as
    Code:
    function()
    {
    	this.attributes["x"] += 100;
    }
    I know you can use Object.prototype.__proto__ to redefine default values for properties (from null to 0). but does this apply to non-existent properties as well?

  2. #2
    Join Date
    Mar 2009
    Posts
    469
    I am not sure of the context, but you might try something like:

    Code:
    function splint(objThatMakeBeLacking, property){
        var default = 100;
        if(!objThatMakeBeLacking[property]){
             return default;
        }
        else{
              return objThatMakeBeLacking[property];
              }
    
    }

  3. #3
    Join Date
    Dec 2002
    Location
    Seattle, WA
    Posts
    1,843
    After a bit of trying out __proto__, get/set, and a bit googling. I found this post on stackoverflow.
    In short, JavaScript does not permit defining default values for unknown properties.
    Not a big deal, this was just an idea I had to reduce redundancy.
    I'll probably do something like this
    Code:
    function Attributes()
    {};
    Attributes.prototype.add = function(key, value)
    {
        this[key] = (this[key] || 0) + value;
    };
    
    function app()
    {
        this.attributes = new Attributes();
    }
    var app = new app();
    app.attributes.add('x', 100);
    Thanks for the reply nonetheless.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles