首頁  >  文章  >  web前端  >  JavaScript呼叫模式與this關鍵字綁定的關係

JavaScript呼叫模式與this關鍵字綁定的關係

不言
不言原創
2018-04-21 16:09:251341瀏覽

這篇文章主要介紹了JavaScript呼叫模式與this關鍵字綁定的關係的相關資料,需要的朋友可以參考下

Invocation 呼叫

呼叫一個函數將暫停目前函數的執行,傳遞控制權和參數給新函數。

實參與形參不一致不會導致運行時錯誤,多的被忽略,少的補為undefined

每個方法都會收到兩個附加參數:this和arguments。 this的值取決於呼叫的模式,呼叫模式:方法,函數,建構器和apply呼叫模式
this被賦值發生在被呼叫的時刻。不同的呼叫模式可以用call方法實作


var myObject = { 
value: 0, 
increment: function (inc) { 
this.value += typeof inc === 'number' ? inc : 1; 
} 
}; 
myObject.double = function(){ 
var helper = function(){ 
console.log(this);// this point to window 
} 
console.log(this);// this point to object myObject 
helper(); 
} 
myObject.double();//myObject Window


1 The Method Invocation Pattern 方法呼叫模式

#方法:函數被儲存為物件的屬性.當方法被呼叫時,this被綁定到該物件

「公共方法:透過this取得他們所屬物件的上下文的方法


myObject.increment(); 
document.writeln(myObject.value); //


底層實作: myObject.increment。 call(myObject,0);

2 The Function Invocation Pattern 函數呼叫模式

當函數並非物件的屬性時就被當作函數呼叫(有點廢話。 this被綁定為undefined

var add = function (a,b) { return a + b;}; 
var sum = add(3,4);// sum的值为7


#底層實作:

add.call(window,3,4)

strict mode:add.call(undefined,3,4)


方法呼叫模式和函數呼叫模式的差異

function hello(thing) { 
console.log(this + " says hello " + thing); 
} 
person = { name: "Brendan Eich" } 
person.hello = hello; 
person.hello("world") // [object Object] says hello world 等价于 person。hello。call(person,“world”) 
hello("world") // "[object DOMWindow]world" 等价于 hello。call(window,“world”)


3 The Constructor Invocation Pattern

JavaScript是基於原型繼承的語言,同時提供了一套基於類別的語言的物件建構語法。

this指向new傳回的物件

var Quo = function (string) { 
this.status = string; 
}; 
Quo.prototype.get_status = function ( ) { 
return this.status; 
}; 
var myQuo = new Quo("this is new quo"); //new容易漏写,有更优替换 
myQuo.get_status( );// this is new quo


#4 The Apply Invocation Pattern

apply和call是javascript的內建參數,都是立刻將this綁定到函數,前者參數是數組,後者要一個個的傳遞apply也是由call底層實現的

apply(this,arguments[]); 
call(this,arg1,arg2...); 
var person = { 
name: "James Smith", 
hello: function(thing,thing2) { 
console.log(this.name + " says hello " + thing + thing2); 
} 
} 
person.hello.call({ name: "Jim Smith" },"world","!"); // output: "Jim Smith says hello world!" 
var args = ["world","!"]; 
person.hello.apply({ name: "Jim Smith" },args); // output: "Jim Smith says hello world!"


相對的,bind函數將綁定this到函數和調用函數分開來,使得函數可以在一個特定的上下文中調用,尤其是事件bind的apply實作

Function.prototype.bind = function(ctx){ 
var fn = this; //fn是绑定的function 
return function(){ 
fn.apply(ctx, arguments); 
}; 
}; 
bind用于事件中 
function MyObject(element) { 
this.elm = element; 
element.addEventListener('click', this.onClick.bind(this), false); 
}; 
//this对象指向的是MyObject的实例 
MyObject.prototype.onClick = function(e) { 
var t=this; //do something with [t]... 
};

相關推薦:


JavaScript呼叫ActiveX操作Oracle資料庫的實例詳解

#淺談JS的this呼叫物件

以上是JavaScript呼叫模式與this關鍵字綁定的關係的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn