標籤:var style 執行個體 prot foo 建立 argument 開始 cto
一、開始
假設我們有一個函數,一個對象
var foo = { value:1}function bar(name,age){ this.hobby = ‘shopping‘; console.log(this.value); console.log(name); console.log(age);}bar.prototype.friend = ‘kevin‘;
我們試一試用原生的bind可以輸出什麼
var bindFoo = bar.bind(foo, ‘daisy‘);var obj = new bindFoo(‘18‘);
可以看到指定原型鏈,指定了this,bind的同時可以傳參數
①指定this,bind的同時穿參數:
我們知道bind返回一個函數並綁定了this,這個類比起來比較簡單
Function.prototype.binds = function(dir){ var self = this; var _args = [].slice.call(arguments,1); return function(){ var args = _args.cancat([].slice.call(arguments)); self.apply(dir,args); } }
②指定原型鏈的指向,即prototype的指向:
Function.prototype.binds = function(dir){ var self = this; var _args = [].slice.call(arguments,1); var inn = function(){ var args = _args.concat([].slice.call(arguments)); self.apply(dir,args); } inn.prototype = new dir(); inn.prototype.constructor = inn; return inn;}
到這裡,如果不去new出一個執行個體的話,都可以了,如果需要new出一個執行個體來,我們就需要重新指定下this,因為如果使用new操作符會把this指向新建立的對象,但我們還是需要他指向原本指向的對象,所以,我們要判斷當前調用對象是否為原對象的一個執行個體屬性,修改後的代碼為:
Function.prototype.binds = function(dir){ var self = this; var _args = [].slice.call(arguments,1); var inn = function(){ var args = _args.concat([].slice.call(arguments)); self.apply(this instanceof self ? this : dir,args); } inn.prototype = new self(); inn.prototype.constructor = inn; return inn;}
到底,我們應該已經完成了對bind的類比,輸出看下結果:
多出的幾個undefined是在new時產生的
Javascript——bind的類比實現