JavaScript中this对象的绑定

调用一个函数将暂停当前函数的执行,传递控制权和参数给新函数。除了声明时定义的形式参数,每个函数接受两个附加的参数:this和arguments 。参数 this 在面向对象编程中非常重要,它的值取决于调用的模式。在JavaScript中一共有四种调用模式:方法调用模式、函数调用模式、构造器调用模式和apply调用模式。
1.方法调用模式
  当一个方法被调用时,this被绑定到该对象。

	var color='green';
	var obj={
		color: 'blue',
		sayColor: function(){
			return this.color;
		}
	};
	document.write(obj.sayColor());//blue 一个方法被调用时,this被绑定到该对象
	document.write(this.color);//green

2.函数调用模式

  当一个函数并非一个对象的属性时,那么它被当作一个函数来使用。

 var sum=add(3,4);//7

  当函数以此模式调用时,this被绑定到全局对象。这是一个语言设计上的错误。倘若语言设计正确,当内部函数被调用时,this 变量应该被绑定到外部函数的this变量。

        var value=1;
        obj.value=5;
	obj.add=function(){
	    var help=function(){
		this.value=add(this.value,1);
	    };
	    help();
	};
	obj.add();
	document.write(value);//2

解决方案为暂时保存外部函数的this值

	obj.add=function(){
	    var that=this;
	    var help=function(){
		that.value=add(that.value,1);
	    };
	    help();
	};
	obj.add();
	document.write(obj.value);//6

3.构造器调用模式

	var Fun=function(string){
		this.name=string;
	};
	Fun.prototype.getName=function(){
		return this.name;
	}
	var obj=new Fun('michael');
	document.write(obj.getName());//michael

4.Apply调用模式

  apply方法让我们构造一个参数数组并用其去调用函数。它也允许我们选择this的值。appl接收两个参数。第一个是将被绑定的this的值。第二个就是一个参数数组。







猜你喜欢

转载自blog.csdn.net/DM_elena/article/details/72778812
今日推荐