gpt4 book ai didi

javascript - 使用 this.property 在原型(prototype)上的方法内返回未定义

转载 作者:行者123 更新时间:2023-12-01 00:39:15 25 4
gpt4 key购买 nike

在下面的代码片段中,我创建了一个事件发射器,它在调用时执行所有事件。我使用了函数构造函数并在其上添加了 onemit 方法。
偶数transfer会更新对象属性amount
但是当我在 on 内访问 this.amount 时,它返回未定义。
emitter.js

function Account(n) {
this.balance=n;
this.events = {}
}
Account.prototype.on = function(type, listener){
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}

Account.prototype.emmit = function(type){
if(this.events[type]) {
this.events[type].forEach(listener => {

listener();
});
}
console.log("Amount transfered. Total Balance is " + this.balance);
}
module.exports = Account;

app.js

const Account = require('./emitter');

const myAccount = new Account(5);
myAccount.on('transfer', function(amount = 10){
this.balance += amount;
console.log(amount + ' Rs. has been transferrered! Balance is ' + this.balance);
});

myAccount.on('transfer', function(amount = 30){
this.balance += amount;
console.log(amount + 'Rs. has been transferrered! Balance is ' + this.balance);
});

myAccount.on('transfer', function(amount = 40){
this.balance += amount;
console.log(amount + 'Rs. has been transferrered! Balance is ' + this.balance);
});
myAccount.emmit('transfer');

这是我已经尝试过的。
我认为 this.events 已经是一个对象,因此其中的 this 将引用当前对象而不是父对象。
因此尝试访问属性myAccount.amount。它仍然返回未定义
我还尝试将 this 的引用存储在变量 that 中,而不是访问 this.amount 中的属性,而是尝试了 that.amount 仍未定义。

最佳答案

您没有将“this”传递给您的监听器回调函数。

listener() 调用更改为此:

listener.call(this);

关于javascript - 使用 this.property 在原型(prototype)上的方法内返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57835649/

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