首页 > 解决方案 > (javascript) 使用“call”调用 es6 getter

问题描述

我正在尝试创建一个(类)实例来复制另一个类的行为,但将其自身用作状态上下文(this)。普通函数可以正常工作(如下setValue例中的函数),但 getter 不起作用。这是一个简单的例子:

const should = require('chai').should();

class One {
    setValue(val) {
        this._val = val;
    }

    get val() {
        return this._val;
    }
}

class Two {
    constructor(one) {
        this.one = one;
    }

    setValue(val) {
        this.one.setValue.call(this, val);
    }

    get val() {
        this.one.val.call(this);
    }
}

let one = new One();
let two = new Two(one);
one.setValue(1);
two.setValue(2);
one.val.should.equal(1);
two.val.should.equal(2);

上面的代码在最后一行爆炸并出现错误:

TypeError: this.one.val.call is not a function
    at Two.get val [as val] (C:\all\code\node-tests\invoke_getter.js:23:22)
    at Object.<anonymous> (C:\all\code\node-tests\invoke_getter.js:32:5)

我怎样才能使这样的工作?

标签: javascriptnode.jsecmascript-6es6-class

解决方案


回想一下,类的属性获取器在其原型中结束

因此,要访问该方法,您可能希望从其原型中获取它:

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.one), 'val')

然后你可以在你的two实例上调用 getter:

class One {
  setValue(val) {
    this._val = val
  }

  get val() {
    return this._val
  }
}

class Two {
  constructor(one) {
    this.one = one
  }

  setValue(val) {
    this.one.setValue.call(this, val)
  }

  get val () {
    const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.one), 'val')
    return desc.get.call(this)
  }
}

const one = new One()
const two = new Two(one)
one.setValue(1)
console.log(two.val) // undefined (since _val does not exist on two yet)
two.setValue(2)
console.log(two.val) // 2
two._val = 3
console.log(two.val) // 3


推荐阅读