国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript調用模式與this關鍵字綁定的關系

2024-05-06 15:19:50
字體:
來源:轉載
供稿:網友

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!"             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 雷州市| 延津县| 仙桃市| 高要市| 精河县| 务川| 高陵县| 泸定县| 左云县| 六枝特区| 和硕县| 和政县| 望奎县| 那坡县| 丹东市| 宜兴市| 阜南县| 于都县| 衡阳市| 资中县| 泾阳县| 织金县| 法库县| 陕西省| 京山县| 蕲春县| 闽清县| 循化| 囊谦县| 夏津县| 峨山| 赣榆县| 始兴县| 榆社县| 湖口县| 黔西县| 广州市| 嘉定区| 泾川县| 阿勒泰市| 庆阳市|