How do I call variable in function?
This question already has an answer here:
Try by assigning this
to a variable:
var XClass = function () {
var that = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}
This way, that
will refer to the current XClass object. Otherwise, inside a event handler callback, this
refers to the object being clicked.
分配this
变量:
var XClass = function () {
var self = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(self.dataMember); // no error
});
}
使用bind
来设置上下文
var XClass = function () {
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(this.dataMember); //error
}.bind(this));
}
链接地址: http://www.djcxy.com/p/94900.html
上一篇: 如何在嵌套对象中使用'this'?
下一篇: 我如何在函数中调用变量?