首頁  >  文章  >  web前端  >  呼叫模式與this綁定

呼叫模式與this綁定

php中世界最好的语言
php中世界最好的语言原創
2018-06-06 17:41:491414瀏覽

這次帶給大家呼叫模式與this綁定,呼叫模式與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被綁定到全域物件(window)

ECMAScript5中新增strict mode, 在這種模式中,為了儘早的暴露出問題,方便調試。 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]... 
};

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

nodejs操作excel檔案

#怎麼做出下滑頁面底部無限載入資料需求

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

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