【问题标题】:Does a getter with Object.defineProperty have access to the instance? [duplicate]具有 Object.defineProperty 的 getter 是否可以访问该实例? [复制]
【发布时间】:2017-10-24 20:55:47
【问题描述】:

假设有一个人:

const Person = function(fname, lname) {
    this.fname = fname;
    this.lname = lname;
};

我想用一个“名称”getter 来扩展它的功能

Object.defineProperty(Person.prototype, 'name', {
  get: () => `${this.fname} ${this.lname}`
});

但是,这不起作用。 getter 中的this 不是调用它的实例原型:

const p = new Person('Taylor', 'Swift');
p.name // "undefined undefined"

而是属性定义的范围:

fname = 'Someone';
lname = 'Else';
p.name // "Someone Else"

【问题讨论】:

    标签: javascript ecmascript-6 this defineproperty


    【解决方案1】:

    在写这个问题的过程中,答案是显而易见的。仍然发布以防它帮助其他人。

    Getter 属性确实绑定到它们的宿主对象。

    问题是我为 getter 使用了箭头函数。箭头函数没有自己的this,而是使用封闭执行上下文的this 值。

    这意味着为 getter 属性完成的binding 无效。

    例如:

    const foo = () => this.document;
    foo() // global document object
    foo.call({document: 'na'}) // still global document object
    const bar = foo.bind({document: 'na'});
    bar(); // still global document object
    

    【讨论】:

      猜你喜欢
      • 2014-01-26
      • 1970-01-01
      • 2014-03-15
      • 1970-01-01
      • 2016-06-08
      • 2012-09-10
      • 1970-01-01
      • 2013-04-02
      • 2019-05-07
      相关资源
      最近更新 更多