gpt4 book ai didi

javascript - (javascript) 使用 "call"调用 es6 getter

转载 作者:行者123 更新时间:2023-12-05 00:38:31 25 4
gpt4 key购买 nike

我正在尝试创建一个(类)实例来复制另一个类的行为,但将其自身用作状态上下文(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)

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

最佳答案

回想一下,类的属性 getter 以它的 prototype 结尾。

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

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

关于javascript - (javascript) 使用 "call"调用 es6 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com