this是一个引用。下面有5种this的变化情况:
1.在函数运行时,每个函数都有一个调用它的上下文,而这个this就是指向这个上下文对象。
example:
var test = function(){
console.log(this);
}
test();//输出window对象
var test = function(){
var attr1 = 'hello';
console.log(this);
console.log(this.attr1);
}
test();//输出window对象和undefined
//Temp构造函数
var Temp = function (attr1,func){
this.attr1 = attr1;
this.test = func;
}
var temp = new Temp("world",test);
temp.test();//输出Temp对象和world
2.在构造函数里this指向该函数创建的实例对象的引用,对象Object里this指向该对象引用,我们就可以轻易在该这些对象里调用自己的方法和属性。
example:
//这是test构造函数
var Test = function (attr1, attr2){
this.attr1 = attr1;
this.attr2 = attr2;
this.func = function(){
console.log(this);//Test创建的对象实例
console.log(this.attr1);//attr1的值
console.log(Test.attr1);//undefined
}
};
//这是object对象
var object = {
attr1 : 'hello ',
attr2 : 'world',
func : function (){
console.log(this);//object对象
console.log(this.attr1);//hello
console.log(object.attr1);//hello
}
}
var temp = new Test('hello', 'world');
temp.func();//输出Test对象 ,hello, undefined
object.func();//输出object对象, hello, hello
example:
var Test = function (attr1, attr2){
this.attr1 = attr1;
this.attr2 = attr2;
this.func = function(){
console.log(this);//Test创建的对象实例
var inner = (function(){
console.log(this);//window对象
})();
}
};
//这是object对象
var object = {
attr1 : 'hello ',
attr2 : 'world',
func : function (){
console.log(this);//object对象
var inner = (function(){
console.log(this);//window对象
})();
}
}
var temp = new Test('hello', 'world');
temp.func();//输出Test对象实例 ,hello, undefined
object.func();//输出object对象, hello, hello
4.事件函数,this指向触发的元素。
example:
<!doctype html>
<html>
<head>
<title>Test</title>
<script>
window.onload = funciton(){
document.getElementById('test').οnclick=function(){
console.log(this);//输出触发的button对象
};
}
</script>
</head>
<body>
<button id="test'>click me!</button>
</body>
</html>
5.call和apply方法可以改变函数的this。在调用call和apply方法时,传入要this指向的对象。
example:
var test = function(){
console.log(this);
console.log(this.attr1);
}
var object = {
attr1 : 'hello',
attr2 : 'world'
}
test();//window对象,undefined, [from window]
test.call(object,null);//object对象,hello ,["this ", "is ", "call"]
test.apply(object,null);//object对象,hello,["this ", "is ", "apply"]
call和apply的区别是:call只能一个一个参数传入,而apply传入的是数组。