javascript call和apply,javascriptapply

來源:互聯網
上載者:User

javascript call和apply,javascriptapply

ref:   http://www.cnblogs.com/fighting_cp/archive/2010/09/20/1831844.html

1、call(), apply()都屬於Function.prototype的一個方法,它是JavaScript引擎內在實現的,因為屬於Function.prototype,所以每個Function對象執行個體,也就是每個方法都有call,      apply屬性,即每個函數都包含兩個非繼承而來的方法:apply()和call(),並且作用一樣。

2、區別參數不一樣如:foo.call(this, arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)

用例1:

                var name = 'window name';test1();  // 彈出 window name 此時test1中的this 為 window對象function test1(){alert(this.name);}var obj = {name:'obj name'}test1.call(obj);//彈出 obj name test中的this為obj ,參數預設為空白//test1.apply(obj) 和call是一樣的結果alert(JSON.stringify(obj));//可以看到obj中並沒有test1函數

call 和 apply 的神奇之處 可以無中生有 讓obj調用test1函數,但並不擁有該函數

用例2:

<span style="white-space:pre"></span>function Animal(name){this.name = name;this.showName = function(){alert(this.name);}};function Cat(name){Animal.call(this,name);}//Cat.prototype = new Animal();function Dog(name){Animal.call(this,name);}//Dog.prototype = new Animal(); // 可以理解為Dog繼承Animalvar cat = new Cat("Black Cat");var dog = new Dog(["Black Dog"]);cat.showName();  //Black Catdog.showName();  //Blcak Dogalert(cat instanceof Animal); //falsealert(dog instanceof Animal); //false  如果放開上面兩行被注釋掉的代碼  則結果為 true
使用Javascript中建構函式讓 cat 、 dog在構造時直接調用animal的建構函式 。

聯繫我們

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