获取“这个”背景下
问题描述:
我试图创建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();
+0
谢谢!两种方法都运行良好,只是发现这一点有点简单。 – sdvnksv
答
您可以使用箭头功能,这将保留您的这上下文。
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();
可能重复[将正确的“this”上下文设置为setTimeout回调?](http://*.com/questions/2130241/pass-correct-this-context-to-settimeout-callback) – Andreas
严重的是,你有在你的代码中已经绑定了... – Adam