call與apply の 區別

來源:互聯網
上載者:User

標籤:運行   繼承   apply   通過   調用   資料   理解   class   app   

/** * 用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以運行結果為:alert(4); */function add(a,b){    alert(a+b);}function sub(a,b){}add.call(sub, 3, 1);//alert 4
/** * call 的意思是把 animal 的ShowName方法放到cat上執行;所以運行結果為:alert(‘Cat‘); */function Animal(name){    this.name = ‘Animal‘;    this.ShowName = function(){        alert(this.name);    }}function Cat(name){    this.name = "Cat";}var animal = new Animal();var cat = new Cat();animal.ShowName.call(cat);
/*** Animal.call(this) 的意思就是使用 Animal對象代替this對象,那麼 Cat中不就有Animal的所有屬性和方法了嗎,Cat對象就能夠直接調用Animal的方法以及屬性了.* */function Animal(name,name2){    this.name = name;    this.name2 = name2;    this.ShowName = function(){        alert(this.name);        alert(this.name2);    }}function Cat(name1,name){    Animal.call(this,name1,name);}var cat = new Cat(‘我是老虎‘,‘我是病貓‘);cat.ShowName();
/** * Class2同時繼承Class10和Class11 * */function Class10(){    this.ShowSub = function(a,b){        alert(a-b);    }}function Class11(){    this.ShowAdd = function (a,b){        alert(a+b);    }}function Class2(){    Class10.call(this);    Class11.call(this);}
var cls2 = new Class2();
cls2.ShowSub(5,2);//alert(3)
cls2.ShowAdd(7,2);//alert(9)
 

接下來是apply的用法與理解

/** *apply:方法能劫持另外一個對象的方法,繼承另外一個對象的屬性. *call:和apply的意思一樣,只不過是參數列表不一樣. * .call(obj, arg1, arg2, arg3, ...); * .apply(obj,[arg1, arg2, arg3, ...]) *//function Class10(name1,name2){    this.name1 = name1;    this.name2 = name2;    this.ShowName = function(){        alert(‘name1:‘ + this.name1);        alert(‘name2:‘ + this.name2);    }}function Class11(name1,name2,age){    this.age = age;    Class10.apply(this,arguments);//此處,Class11劫持了Class10的屬性[name1,name2,age]與方法ShowName();    this.ShowAge = function(){        alert(‘age:‘ + this.age);    }}var cls = new Class11(‘名字1‘,‘名字2‘,‘好幾歲了‘);cls.ShowName();cls.ShowAge();

代碼大多是網上找的資料,然後自己隨手做了一下小改動,測試通過,便於自己理解-w-

便於理解的格式:

父類.call(子類);

父類.apply(子類,arguments);

 

和C#相反:

class 子類 : 父類 { ... }

 

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.