Appearance
JS中的this
介绍 this 各种情况
- 一般函数中使用 this,这时候一般指向 window
js
function test() {
this.x = 1;
}
test();
console.log(x); // 1- 对象方法中的 this,一般指向上级对象
js
var obj = {
a: 1,
b: {
a: 2,
test: function() {
console.log(this.a);
}
}
};
obj.b.test(); // 2- 构造函数中的 this,一般指向实例对象
js
var a = 1;
function Test() {
this.a = 2;
}
var t = new Test();
console.log(t.a); // 2- apply、call、bind 中的 this,指向第一个参数
js
var a = 0;
var obj = {
a: 1,
b: {
a: 2,
test: function() {
console.log(this.a);
}
}
};
obj.b.test.apply(obj); // 1