简体   繁体   English

了解命名访问器属性属性

[英]Understanding named accessor property attribute

At 8.6.1 sec. 8.6.1秒。 the attributes of named accessor property are given. 给出了命名访问器属性的属性。 Let we are creating named accessor property such as 让我们创建命名的访问器属性,例如

var o=Object.create({},{bar:{get: function(){ return 10;}, 
                             set: function(value){ console.log("o.bar is", value)}}})
o.bar=550;

It's ok. 没关系。 In console we have o.bar is 550 . 在控制台中, o.bar is 550 But i have a some doubts. 但是我有一些疑问。 Named accessor property doesn't have value attribute. 命名访问器属性没有value属性。 So which attribute is assigned to 550? 那么哪个属性分配给550?

How we can return this assigned value? 我们如何返回该赋值? I'm trying to rewrite get function such the following: 我正在尝试重写get函数,如下所示:

get: function(){ return value;}

But I have error: 但是我有错误:

[15:59:41.418] ReferenceError: value is not defined @ http://fiddle.jshell.net/_display/:26

Please explain me how named accessor property works? 请向我解释命名访问器属性如何工作?

Named accesor property doesn't have value attribute. 命名的accesor属性没有value属性。 So which attribute is assigned to 550? 那么哪个属性分配给550?

None, you have to do that in your setter. 没有,您必须在设置器中执行此操作。 It's not done automatically. 它不是自动完成的。

How we can return this assigned value? 我们如何返回该赋值?

From wherever you saved it. 无论您从哪里保存它。 For instance, it's fairly common to use a closure for this (I've put it on multiple lines for clarity) : 例如,为此使用闭包是相当普遍的(为了清楚起见,我将其放在多行中)

var o=Object.create({},(function() {
    var _bar = 10;

    return {
      bar:{
        get: function(){
          return _bar;
        },
        set: function(value){
          _bar = value;
          console.log("bar set to " + _bar);
        }
      }
    };
})());
o.bar=550;
console.log("o.bar = " + o.bar);

Live Example | 现场示例 | Source 资源

Condensed version if you're into that sort of thing: :-) 精简版,如果您喜欢这种东西::-)

var o=Object.create({},(function() {
    var _bar = 10;

    return {bar:{get: function(){ return _bar; },
                 set: function(value){ _bar = value; console.log("bar set to " + _bar); }}};
})());
o.bar=550;
console.log("o.bar = " + o.bar);

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

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