我无法通过嵌套函数识别“this”关键字。这是一个例子。我有一个构造函数:
function person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.changeName = changename;
}
我有另一个带嵌套函数的函数:
function changeName (name) {
this.lastname = name;
$.post("display.php", "some_data", function(data,status) {
if (status=="success") {
alert(this.lastName); //undefined
}
}
}
答案 0 :(得分:2)
该函数从你需要的内部函数设置它。使用.bind或者“hack”:
function changeName (name) {
var that = this;
this.lastname = name;
$.post("display.php", "some_data", function(data,status) {
if (status=="success") {
alert(that.lastName); //undefined
}
}
}
function changeName (name) {
this.lastname = name;
$.post("display.php", "some_data", function(data,status) {
if (status=="success") {
alert(this.lastName); //undefined
}
}.bind(this))
}
这是一个非常好的explanation
答案 1 :(得分:1)
那是因为this
在事件处理程序中是window
。您可以在changeName
范围内定义别名,如下所示:
function changeName (name) {
var p = this;
p.lastname = name;
$.post("display.php", "some_data", function(data,status) {
if (status=="success") {
alert(p.lastName);
}
}
}