JS中this的四种调用模式

在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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值