Javascript——bind的類比實現

來源:互聯網
上載者:User

標籤: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的類比實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.