尽管有点简单,但是当您执行以下代码时,它指向文档,因此您无法获得Hoge的实例。
如果使变量和函数成为全局变量,则闭包中没有定义含义,还有更好的方法吗?
var Hoge = function() {
this.hogehoge = 'hogehoge';
document.addEventListener('mousedown', this.change, false);
};
Hoge.prototype = {
change: function(e) {
e.pageX
console.log(this.hogehoge); // undefined
}
};
let hoge = new Hoge();
我希望console.log
的输出为'hogehoge'
,但实际输出为undefined
。
答案 0 :(得分:0)
您在外部上下文中调用this.change
,您需要像this.change.bind(this)
这样绑定,以使this
上下文保持与单击时相同。
var Hoge = function() {
this.hogehoge = 'hogehoge';
document.addEventListener('mousedown', this.change.bind(this), false);
};
Hoge.prototype = {
change: function(e) {
e.pageX;
console.log(this.hogehoge); // undefined
}
};
let hoge = new Hoge();
有关更多信息,请在此处阅读
this
如何获得其上下文:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this