传送门:JavaScript 教程 / 面向对象编程 / this 关键字 / 4. 使用注意点
1. 【多层this】this赋值给一个变量
- 未处理:
var o = {
f1: function () {
console.log(this); // Object
var f2 = function () {
console.log(this); // Window
}();
}
}
o.f1();
- 处理后:
var o = {
f1: function () {
console.log(this); // Object
var that = this; // this 指向当层环境
var f2 = function () {
console.log(that); // Object
}();
}
}
o.f1();
应用场景:forEach、map【数组处理函数】(另一种解决方法在第三点)
- 未处理:
var o = {
v: 'hello',
p: [ 'a1', 'a2' ],
f: function f() {
this.p.forEach(function (item) {
console.log(this.v + ' ' + item);
});
}
}
o.f();
// undefined a1
// undefined a2
- 处理后:
var o = {
v: 'hello',
p: [ 'a1', 'a2' ],
f: function f() {
var that = this;
this.p.forEach(function (item) {
console.log(that.v+' '+item);
});
}
}
o.f();
// hello a1
// hello a2
2. 【严格模式】this指向顶层对象则报错
- 未处理:
var counter = {
count: 0
};
counter.inc = function () {
this.count++;
};
var f = counter.inc;
f(); // undefined
- 处理后:
var counter = {
count: 0
};
counter.inc = function () {
'use strict';
this.count++;
};
var f = counter.inc;
f(); // Error: ...
3. 【数组处理方法】forEach、map使用第二参数传入this
- 未处理:
var o = {
v: 'hello',
p: [ 'a1', 'a2' ],
f: function f() {
this.p.forEach(function (item) {
console.log(this.v + ' ' + item);
});
}
}
o.f();
// undefined a1
// undefined a2
- 处理后:
var o = {
v: 'hello',
p: [ 'a1', 'a2' ],
f: function f() {
this.p.forEach(function (item) {
console.log(this.v + ' ' + item);
}, this); // 使用第二参数,传入this
}
}
o.f();
// hello a1
// hello a2
4. 【上下文调用】通过call / apply / bind 来绑定 this
var obj = {};
var f = function () {
return this;
};
f() === window // true
f.call(obj) === obj // true