在JS中this有四种调用模式:方法调用模式、函数调用模式、构造器调用模式和apple调用模式
函数与方法的区别:当一个函数被保存为对象的属性时,我们称这个函数为方法。
1、方法调用模式(也就是用"."的方式来调用的)
如果在方法中出现this,此时的this指调用该方法的对象。
<strong><span style="font-size:18px;">var person={
name:"houyanchao",
talk:function(){
<span style="white-space:pre"> </span>alert(this.name);
}
}
person.talk();//houyanchao</span></strong>
talk方法中的this为调用talk()的person对象。
2、函数调用模式
当一个函数中出现this时,此时的this指全局对象(window)
<strong><span style="font-size:18px;">var name = "The Window";
var object = {
<span style="white-space:pre"> </span>name: "My Object",
getNameFunc: function() {
alert(this.name); //My Object
return function() {
alert(this.name); //The Window
};
}
};
alert(object.getNameFunc()());</span></strong>
第五行中的this出现在方法中,所以该this指调用该方法的对象。而第八行的this出现在匿名函数中,此时的this指window对象。所以当调用方法时弹出My Object,调用匿名函数时弹出全局的name变量The Window.
3、构造器调用模式
<span style="font-size:18px;"><strong>function Human(username, age) {
this.username = username;
this.age = age;
this.introduce = function() {
alert(this.username + this.age);
}
}
var person = new Human("houyanchao", 23);
person.introduce();</strong></span>
对象构造函数Human(),函数中的this指调用该构造函数创建的对象person
4、call(或者apply)调用模式
<span style="font-size:18px;"><strong><input type="text" id="myText" value="input text">
<script>
function Obj(){this.value="对象!";}
var value="global 变量";
function Fun1(){alert(this.value);}
Fun1(); <span style="color:#009900;">//global 变量</span>
Fun1.call(window); <span style="color:#33cc00;">//global 变量</span>
Fun1.call(document.getElementById('myText')); <span style="background-color: rgb(255, 255, 255);"><span style="color:#009900;">//input text</span></span>
Fun1.call(new Obj()); <span style="color:#009900;"> //对象!</span>
</script></strong></span>
当使用call调用函数时,第一个参数决定函数中this(this=第一个参数)。此情况同样适用于apply。