我正在尝试在JS中创建一个"类",其简化结构如下:
http://codepen.io/Deka87/pen/WpqYRP?editors=0010
function Alert() {
this.message = "Test alert";
this.document = $(document);
this.document.on('click', function() {
this.show();
}.bind(this));
};
Alert.prototype.show = function() {
setTimeout(function() {
console.log(this.message);
}, 50);
};
var alert = new Alert();
当您单击document
时,它应该会在控制台中显示this.message
内容。但是,它现在显示为 undefined
.我相信问题是this.messsage
无法获得原始this
上下文,因为它是另一个函数的包装器(在我的情况下setTimeout
(。任何帮助将不胜感激!
这是对我有用的方法,您可以通过引用self
来获得this.message
,这是您需要的正确上下文。
function Alert() {
this.message = "Test alert";
this.document = $(document);
this.document.on('click', function() {
this.show();
}.bind(this));
};
Alert.prototype.show = function() {
var self = this;
setTimeout(function() {
console.log(self.message);
}, 50);
};
var alert = new Alert();
您可以使用箭头函数来保留此上下文。
function Alert() {
this.message = "Test alert";
this.document = $(document);
this.document.on('click', () => {
this.show();
});
};
Alert.prototype.show = function () {
setTimeout(() => {
console.log(this.message);
}, 50);
};
var alert = new Alert();
阅读更多:https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions_and_function_scope/Arrow_functions。