前言
this是什么?
它是函数运行时
,在函数体内部自动生成的一个对象,只能在函数体内部使用
function test() {
this.name = "hamsterY";
}
// 函数没有运行,指向无法确定
this指向谁?
在函数运行的时候,this指向最终调用它的那个对象
下文中的情况一、二
会对这句话做出详细解释
情况一:普通函数调用
// Demo1
var a = 1;
function test() {
console.log(this.a);
};
test();// 结果:1
这个test函数的调用,写完整后其实是window.test()
,只不过window我们一般省略
像常用的console,alert
也都是window下的方法,window都省略了
var a = 1;
function test() {
console.log(this.a);
};
window.test();// 结果是一样的
上面这个Demo是window调用了test函数,所以this指向window
这个例子证明了
this指向调用它的那个对象
情况二:作为对象的方法调用
// Demo2
var obj = {
a: 1,
b: function() {
console.log(this.a);
}
}
obj.b()// 结果:1
因为o调用了b(),所以this指向o
按照Demo1的做法,把前面的window对象补上
var obj = {
a: 1,
b: function() {
console.log(this.a);
}
}
window.obj.b()
发现b函数前面有两个对象
然而this并未指向最外层的window
,而是指向了较近的o
到这里就可以证明开头那句话
this指向最终 调用它的那个对象
如果不放心,可以再看一个例子
// Demo3
var obj = {
a: 1,
b: {
a: 2,
test: function() {
console.log(this.a);
}
}
}
obj.b.test();// 结果:2
this指向了最近的b
对象
到这里一般情况的this指向已经说明白了,接下来是一些特殊情况。
情况三:作为构造函数调用
function test() {
this.x = 1;
}
var obj = new test();
obj.x // 1
通过new关键字,生成的新对象——obj
,this指向这个新对象
在上面这个demo中,this就指向obj
情况四:call、apply、bind改变this指向
这三个原生的方法可以手动改变this的指向,简单举个例子
function test() {
console.log(this);
};
var obj = {
name: 'hamstery'
}
test.call(obj);// this指向obj
test.apply(obj);// this指向obj
以上仅个人理解,如有错误请大家指正,多谢!