[英]Add function to constructor prototype with method with access to this from constructor instance
我想要以下代碼中的注釋所期望的結果:
// 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的重復-正如我所認為的,這由下面的解決方案證明。
如果您確實需要此屬性在原型中,則可以使用自定義屬性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
。
您可以將getter與Object.assign()
一起使用:
// constructor function As(data) { this.data = data } function helloWorld() { console.log(this.data) } Object.defineProperty(As.prototype, 'helloWorld', { get() { return Object.assign(helloWorld, { myMethod: () => { console.log(this.data) }, }) }, }) const asI = new As('some data') asI.helloWorld() // => 'some data' asI.helloWorld.myMethod() // => 'some data'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.