关于 this
this 引用的是函数据以执行的环境对象。
var point = {
moveTo: function (x, y) {
// 内部函数
var moveX = function (x) {
this.x = x; //this 绑定到了哪里?
};
// 内部函数
var moveY = function (y) {
this.y = y; //this 绑定到了哪里?
};
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x); // undefined
console.log(point.y); // undefined
console.log(x); // 1
console.log(y); // 1
moveTo: function (x, y) {
// 内部函数
var moveX = function (x) {
this.x = x; //this 绑定到了哪里?
};
// 内部函数
var moveY = function (y) {
this.y = y; //this 绑定到了哪里?
};
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x); // undefined
console.log(point.y); // undefined
console.log(x); // 1
console.log(y); // 1
可以看到:在一个对象的方法内部再创建内部函数,内部函数中的 this 指向的是 window 对象,要想让 this 指向创建的那个对象,可以用 that 替换掉 this,如:
var point = {
moveTo: function (x, y) {
var that = this; // 用 that 代替 this
// 内部函数
var moveX = function (x) {
that.x = x; //this 绑定到了哪里?
};
// 内部函数
var moveY = function (y) {
that.y = y; //this 绑定到了哪里?
};
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x); // 1
console.log(point.y); // 1
moveTo: function (x, y) {
var that = this; // 用 that 代替 this
// 内部函数
var moveX = function (x) {
that.x = x; //this 绑定到了哪里?
};
// 内部函数
var moveY = function (y) {
that.y = y; //this 绑定到了哪里?
};
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x); // 1
console.log(point.y); // 1