gpt4 book ai didi

javascript - 使用可以从构造函数实例访问 this 的方法将函数添加到构造函数原型(prototype)

转载 作者:行者123 更新时间:2023-11-30 14:37:47 25 4
gpt4 key购买 nike

我希望按照下面代码中的注释得到期望的结果:

// constructor
function As(data) {
this.data = data
}

function helloWorld() {
console.log(this.data)
}

helloWorld.myMethod = {
// ...do sideffect
// desired: execute helloWorld here bound against `asI`
}

As.prototype.helloWorld = helloWorld


const asI = new As('some data')
asI.helloWorld() // => 'some data'

// desired
asI.helloWorld.myMethod() // desired result: => 'some data'

编辑:这不是 JavaScript - this of this 的副本如我所想,下面的解决方案证明了这一点。

最佳答案

如果你真的需要这个属性在原型(prototype)中,你可以使用自定义属性 getter。

// constructor
function As(data) {
this.data = data
}


Object.defineProperty(As.prototype, 'helloWorld', {
get: function() {
function helloWorld() {
console.log(this.data)
}

helloWorld.myMethod = (function(){
console.log(this.data)
}).bind(this);

return helloWorld;
}
});



const asI = new As('some data')
asI.helloWorld() // => 'some data'

// desired
asI.helloWorld.myMethod() // desired result: => 'some data'

请记住,每次访问 helloWorld 时,这种天真的实现都会创建新函数。

关于javascript - 使用可以从构造函数实例访问 this 的方法将函数添加到构造函数原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50150554/

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