简体   繁体   English

为什么这种特殊的JavaScript代码以这种方式工作?

[英]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 ? 为什么getFoo是函数而不是value

Because Object.create takes property descriptors as input : 因为Object.create属性描述符作为输入:

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. 如果指定且未undefined ,则其可枚举的自身属性(即,在其自身上定义的那些属性,而不是其原型链上不可枚举的属性)的对象将指定要添加到新创建的对象的属性描述符,并带有相应的属性名称。

and value means: value表示:

value
The value associated with the property. 与属性关联的值。 (data descriptors only). (仅数据描述符)。 Defaults to undefined . 默认为undefined

But as getFoo implies, it might be better to define it as accessor property : 但是正如getFoo所暗示的,最好将其定义为accessor属性

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. 很抱歉,这1行代码来自JavaScript控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM