JavaScript調(diào)用模式與this關鍵字綁定的關系
Invocation 調(diào)用
調(diào)用一個函數(shù)將暫停當前函數(shù)的執(zhí)行,傳遞控制權和參數(shù)給新函數(shù)。
實參與形參不一致不會導致運行時錯誤,多的被忽略,少的補為undefined
每個方法都會收到兩個附加參數(shù):this和arguments。this的值取決于調(diào)用的模式,調(diào)用模式:方法,函數(shù),構造器和apply調(diào)用模式
this被賦值發(fā)生在被調(diào)用的時刻。不同的調(diào)用模式可以用call方法實現(xiàn)
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 方法調(diào)用模式
方法:函數(shù)被保存為對象的屬性.當方法被調(diào)用時,this被綁定到該對象
公共方法:通過this取得他們所屬對象的上下文的方法
myObject.increment(); document.writeln(myObject.value); //
底層實現(xiàn): myObject.increment。call(myObject,0);
2 The Function Invocation Pattern 函數(shù)調(diào)用模式
當函數(shù)并非對象的屬性時就被當作函數(shù)調(diào)用(有點廢話。。),this被綁定到全局對象(window)
ECMAScript5中新增strict mode, 在這種模式中,為了盡早的暴露出問題,方便調(diào)試。this被綁定為undefined
var add = function (a,b) { return a + b;}; var sum = add(3,4);// sum的值為7
底層實現(xiàn):add.call(window,3,4)
strict mode:add.call(undefined,3,4)
方法調(diào)用模式和函數(shù)調(diào)用模式的區(qū)別
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容易漏寫,有更優(yōu)替換 myQuo.get_status( );// this is new quo
4 The Apply Invocation Pattern
apply和call是javascript的內(nèi)置參數(shù),都是立刻將this綁定到函數(shù),前者參數(shù)是數(shù)組,后者要一個個的傳遞apply也是由call底層實現(xiàn)的
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函數(shù)將綁定this到函數(shù)和調(diào)用函數(shù)分離開來,使得函數(shù)可以在一個特定的上下文中調(diào)用,尤其是事件bind的apply實現(xiàn)
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調(diào)用模式與this關鍵字綁定的關系 ,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!