這里的文章會同步到掘金
在js中,經(jīng)常會用到apply
,call
, bind
, new
,這幾個方法在前端占據(jù)非常重要的作用,今天來看一下這些方法是如何實現(xiàn),方便更加深入的理解它們的運作原理。
this的綁定問題
引用一點點其他知識點:一個方法的內(nèi)部上下文this
如何確定?
一個方法的調(diào)用分為一下四種:
方法直接調(diào)用,稱之為函數(shù)調(diào)用,當前的上下文this,綁定在全局的
window
上,在嚴格模式use strict
下,this
為null
-
方法作為一個對象的屬性,這個是否通過對象調(diào)用方法,
this
綁定在當前對象上。如下:let dog = { name: '八公', sayName: function() { console.log(this.name) } } dog.sayName() // 八公
-
apply
,call
調(diào)用模式,當前的方法的上下文為方法調(diào)用的一個入?yún)?/strong>,如下:function sayHello() { console.log(this.hello) } let chineseMan = { hello: '你好啊' } sayHello.apply(chineseMan) // 你好啊 let englishMan = { hello: 'how are you' } sayHello.apply(englishMan) // how are you
-
構(gòu)造函數(shù)的調(diào)用,當前方法的上下文為新生的實例,如下
// 聲明構(gòu)造函數(shù) function Animal(name) { this.name = name this.sayName = function() { console.log(this.name) } } let dog = new Animal('dog') dog.sayName() // dog let cat = new Animal('cat') cat.sayName() // cat
正文
apply實現(xiàn)
思路:apply方法實現(xiàn)在Function.prototype中
獲取到當前調(diào)用方法體
獲取方法的入?yún)?/p>
綁定方法體中的上下文為傳入的context--使用的方法就是對象調(diào)用屬性方法的方式綁定
-
調(diào)用方法
Function.prototype.myApply = function() { let _fn = this if (typeof _fn !== 'function') { throw new TypeError('error') } let ctx = [...arguments].shift() // 因為apply的入?yún)⑹菙?shù)組,所有只需要取第一個 let args = [...arguments].slice(1).shift() ctx.myApplyFn = _fn // 由于apply會將原方法的參數(shù)用數(shù)組包裹一下,所以需要展開參數(shù) let res = ctx.myApplyFn(...args) delete ctx.myApplyFn return res }
call實現(xiàn)
思路:實現(xiàn)在Function.prototype中,大致和apply相似,卻別在對于參數(shù)的處理上
獲取到當前調(diào)用方法體
獲取方法的入?yún)?/p>
綁定方法體中的上下文為傳入的context
-
調(diào)用方法
Function.prototype.myCall = function() { let _fn = this if (typeof _fn !== 'function') { throw new TypeError('error') } let ctx = [...arguments].shift() // call使用的多個入?yún)⒌姆绞剑兄苯尤?shù)第二個參數(shù)開始的所有入?yún)ⅲb成一個數(shù)組 let args = [...arguments].slice(1) ctx.myCallFn = _fn let res = ctx.myCallFn(...args) delete ctx.myCallFn return res }
bind實現(xiàn)
思路:實現(xiàn)在Function.prototype中,并且返回一個已經(jīng)綁定了上下文的函數(shù)。利用閉包可以捕獲函數(shù)上下文的變量來實現(xiàn),總體上比起之前兩個方法稍微復(fù)雜一些。
獲取調(diào)用bind的實例方法體
獲取需要綁定的上下文context
聲明閉包函數(shù)
閉包函數(shù)中綁定context到實例方法體中
閉包函數(shù)中調(diào)用原來的方法體
-
返回閉包函數(shù)
Function.prototype.myBind = function() { let _fn = this if (typeof _fn !== 'function') { throw new TypeError('error') } let ctx = [...arguments].shift() let args = [...arguments].slice(1) return function() { // 因為bind的調(diào)用方式,會有bind({}, 'para1', 'para2')('para3', 'para4'),這個時候需要將外面參數(shù)和內(nèi)部參數(shù)拼接起來,之后調(diào)用原來方法 args = args.concat([...arguments]) ctx.myBindFn = _fn let res = ctx.myBindFn(...args) delete ctx.myBindFn return res } }
codepen演示
<p class="codepen" data-height="265" data-theme-id="0" data-default-tab="js,result" data-user="beyondverage0908" data-slug-hash="PXMyqB" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="rewrite bind">
<span>See the Pen <a >
rewrite bind</a> by avg (<a >@beyondverage0908</a>)
on <a >CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
new 方法實現(xiàn)
思路:需要明白new到底做了什么
生成一個新的實例對象
實例對象
__proto__
鏈接到構(gòu)造函數(shù)的prototype對象綁定構(gòu)造函數(shù)的上下文為當前實例
-
獲取參數(shù),傳入?yún)?shù),并調(diào)用構(gòu)造函數(shù)
function newObj() { let _o = {} let constructor = [...arguments].shift() let args = [...arguments].slice(1) if (typeof constructor !== 'function') { throw new TypeError('error') } _o.__proto__ = constructor.prototype // 第一種調(diào)用方式:借助apply,call,或者bind實現(xiàn)綁定_o // constructor.apply(_o, args) // 第二種,使用屬性方法綁定的方式 _o.myNewFn = constructor _o.myNewFn(...args) delete _o.myNewFn return _o } // how to use - 如何使用 function Animal(name, weight) { this.name = name this.weight = weight } let dog = newObj(Animal, 'dog', '18kg') // the animal name: dog weight: 18kg console.log(`the animal name: ${dog.name} weight: ${dog.weight}`) let cat = newObj(Animal, 'cat', '11kg') // the animal name: cat weight: 11kg console.log(`the animal name: ${cat.name} weight: ${cat.weight}`)
codepen
<p class="codepen" data-height="265" data-theme-id="0" data-default-tab="js,result" data-user="beyondverage0908" data-slug-hash="MZNPoK" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid black; margin: 1em 0; padding: 1em;" data-pen-title="MZNPoK">
<span>See the Pen <a >
MZNPoK</a> by avg (<a >@beyondverage0908</a>)
on <a >CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
結(jié)語
熟悉函數(shù)內(nèi)部的實現(xiàn),了解內(nèi)部的原理,對理解運行會有很多好處,親自實現(xiàn)一遍會給你很多領(lǐng)悟。同時這些知識點又是非常重要的。