Javascript 如何在函数中调用变量?
请参考以下代码Javascript 如何在函数中调用变量?,javascript,Javascript,请参考以下代码 var XClass = function () { this.dataMember = "hello world"; $("div").on("click", "button", function() { console.log(this.dataMember); //error }); } 如何在功能中访问此.dataMember?我在js上搜索了新内容。使用bind设置上下文 var XClass = function
var XClass = function () {
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(this.dataMember); //error
});
}
如何在功能中访问此.dataMember?我在js上搜索了新内容。使用
bind
设置上下文
var XClass = function () {
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(this.dataMember); //error
}.bind(this));
}
使用
bind
设置上下文
var XClass = function () {
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(this.dataMember); //error
}.bind(this));
}
尝试将此
赋值给变量:
var XClass = function () {
var that = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}
var XClass = function () {
var self = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(self.dataMember); // no error
});
}
这样,将引用当前的XClass对象。否则,在事件处理程序回调中,此
引用正在单击的对象。尝试将此
指定给变量:
var XClass = function () {
var that = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}
var XClass = function () {
var self = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(self.dataMember); // no error
});
}
这样,将引用当前的XClass对象。否则,在事件处理程序回调中,此
引用正在单击的对象。将此
分配给变量:
var XClass = function () {
var that = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}
var XClass = function () {
var self = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(self.dataMember); // no error
});
}
将此分配给变量:
var XClass = function () {
var that = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(that.dataMember);
});
}
var XClass = function () {
var self = this;
this.dataMember = "hello world";
$("div").on("click", "button", function() {
console.log(self.dataMember); // no error
});
}
我认为这是一个更好的复制品:我认为这是一个更好的复制品: