David G
David G

Reputation: 96810

Why does this particular JavaScript code work this way?

var my_obj = Object.create({}, {
    getFoo: {
        value: function() {
            return this.foo;
        }
    }
});
my_obj.foo = 1;

alert(my_obj.getFoo());

Why is getFoo the function instead of value?

Upvotes: -1

Views: 89

Answers (2)

GAgnew
GAgnew

Reputation: 4083

Actually.. its just because you set value to equal a function.

If you were trying to run that function anonymously, you have to include that after the declaration. Observe:

x = { y : function(){return 2;}}

x.y
function (){return 2;}

x = {y : function(){return 2;}()}

x.y
2 

Note the trailing () after the function declaration.

Sorry for the 1 line code, came right from a javascript console.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

Because Object.create takes property descriptors as input :

propertiesObject

If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.

and value means:

value
The value associated with the property. (data descriptors only). Defaults to undefined.

But as getFoo implies, it might be better to define it as accessor property:

var my_obj = Object.create({}, {
    foo: {
        get: function(){ 
            return this._foo; },
        set: function(newValue){ 
            this._foo = newValue; 
        }
    }
});

Upvotes: 4

Related Questions