js的call,apply,bind的使用與區別

來源:互聯網
上載者:User

標籤:調用   demo   ons   相容   --   是你   name   ror   執行函數   

在原生js中會有三個很常見的函數,call,apply,bind

他們的作用就是改變當前函數的this指標,

但是細微來說他們還是有不同的。

1)call,apply都是執行某一函數,發現this有變得時候才使用的(進行時)

2)bind是在函數進行調用之前,就強行給變了this的指向(進行前),它的效果是返回一個函數(只是給變了this指向)

說的很多了,不說了

demo :

    function Foo(name){        this.name=name;    }    Foo.prototype.getName=function(){        return this.name;    }    function Bar(name,label){        Foo.call(this,name);        this.label=label;    }    Bar.prototype.getMylabel=function(){            return this.label;    }    var fo=new Foo(‘一燈‘);      console.log(fo.getName());  //一燈    var ba=new Bar("是你的?","大家的");     console.log( ba.getMylabel());    //大家的

console.log(ba);//bar{label:大家的,name:是你的?}

明白人都會有個問題,這個ba怎麼將name值賦值成功的,因為他沒有Foo方法呀?

這就是call的厲害了。慢慢體會其中奧秒,

 

一個問題怎麼把call換成apply???

只需要這樣: Foo.call(this,name);要被改變成--->Foo.apply(this,[name]).....多說一句,applay與call的卻別就是applay的參數是一個數組,

 

第二個問題:怎麼換成bind呢????

已經說過bind的使用是函數進行前進行操作的,返回一個函數

 var setName=Foo.bind(this);

 setName(name); 

當然也可以寫成一句話:Foo.bind(this)(name);表面上來看,好像只是與call多了一個括弧,但是含義確實不同,bind是先返回一個函數,然後執行函數,,,,,,


第三個問題:我要怎麼輸出我的ba中的name呢???

很簡單呀:console.log(ba.getName());

嗯,錯了,確實錯了,ba沒有getName()方法呀。

怎麼辦了,這裡

方法不唯一.

第一種方法:

console.log(Foo.prototype.getName.call(ba));

或者  console.log(Foo.prototype.getName.bind(ba)());

 console.log(Foo.prototype.getName.apply(ba));

 第二種方法:

Bar.prototype=Object.create(Foo.prototype);

console.log(ba.getName());//是你的?

【Objecrt.create的作用就是將Foo.prototype與Bar.prototype相關聯起來】

console.log(ba.getMylable());//error       出錯了什麼鬼???????

【忘記說了,Object.create()他會出建立一個新對象,這樣Bar.prototype就會被替換了,這樣就尷尬了,getMylabel()就丟了。。。。。。。】

聰明的孩紙說:那麼就這樣來:

  Bar.prototype=Object.create(Foo.prototype);  Bar.prototype.getMylabel=function(){       return this.label;  }

一點毛病也沒用,很好。

其實能更高雅點,當你翻開你的課本,你就會發現其實,Object.setPrototypeOf(Bar.prototype,Foo.Prototype)即可規避上面的尷尬現象了,

Object.setPrototypeOf(Bar.prototype,Foo.Prototype)會改變前者的一些東西,不會將他拋棄

 

到這裡我已經沒什麼好說的,只想說,bind函數具有一定的相容性問題

 

js的call,apply,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.