1. 程式人生 > >JavaScript中this物件的繫結

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的值。第二個就是一個引數陣列。