Javascript call和apply的類比實現

來源:互聯網
上載者:User

標籤:i++   cal   分享   arguments   alt   變化   this   新特性   但我   

一、開始

我們先看下原生call做了什麼事

function bar(name,age){    this.hobby = ‘shopping‘;    console.log(this.value);    console.log(this.hobby);    console.log(name);    console.log(age);}bar.prototype.friend = ‘kevin‘;var obj = {    hobby: ‘gamming‘}var hah = bar.call(obj,‘jack‘,18);

輸出是:

這說明call只是修改了this的指向,沒有返回對象。

二、類比實現

所以我們只要嘗試著去修改this的指向並執行就行了,不需要有傳回值:

Function.prototype.calls = function(){    var dir = arguments[0];    var args = [];    for(var i = 1; i < arguments.length; i++){        args.push(arguments[i])    };    dir.pau = this;    // 這裡用到了ES6的新特性,不好    dir.pau(...args);    delete dir.pau;}

如果不像用es6,我看別人的方法則是用了eval,但我不懂eval……

 eval(‘dir.pau(‘ + args +‘)‘); delete dir.pau;

三、apply

apply只是把call一個一個參數傳遞的形勢變成直接傳遞一個數組而已,並沒有多大變化,這裡就不繼續寫了

Javascript call和apply的類比實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.