开发者

Why does this particular JavaScript code work this way?

var my_obj = Object.开发者_JAVA百科create({}, {
    getFoo: {
        value: function() {
            return this.foo;
        }
    }
});
my_obj.foo = 1;

alert(my_obj.getFoo());

Why is getFoo the function instead of value?


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; 
        }
    }
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜