apply()方法和call()方法

來源:互聯網
上載者:User

標籤:

obj.func.call(obj1)       //是將obj1看做obj,調用func方法,將第一個參數看做函數調用的對象,可以看做,將obj的方法給obj1使用

 

ECMAScript規範給所有函數都定義了call()與apply()方法。

 

注意:call()與apply()的第一個參數都是需要調用的函數對象。

     在函數體內this的值就是指向這個調用者,也就是第一個參數,剩餘的參數都是需要傳遞給函數的值

     call()與apply()的不同在於,剩餘的參數,call(),剩餘的參數可以是任意的值,而apply()剩餘的值只能是數組。

 

例如:function add(a,b){  

    return a+b;

  }

  function sub(a,b){

  return a-b;

}

apply()的用法:

  var a1=add.apply(add,[4,2]);

  var a2=sub.apply(sub,[4,2]);

call()的用法:

  var a1=add.call(add,4,2);

  var a2=sub.call(sub,4,2);

 

Js認為他自己是萬能的,既然進階語言能夠繼承,我JS也可以繼承

  function fun1(){

  this.a=123;

  this.add=function(){

    return this.a;

  }

  function fun2(){

    this.a=456;

  }

}

 

  var a1=new fun1();

  var a2=new fun2();

  var a=a1.add.call(a2); //輸出的是456

 

這裡就是把f1的方法拿給f2來使用,f2便可以使用f1中所有的方法,這不正是進階語言中繼承的概念嗎,而且還可以模仿進階語言中的多繼承

function fun1(){

  this.add=function(){

    return this.a+this.b;

  }

  this.fun2=function(){

    return this.a-this.b;

  }

  funtion fun3(){

    this.a=10;

    thi.b=2;

    fun1.call(this);

    fun2.call(this);

  }

}

 

var f3=new fun3();

console.log(f3.add())  //13;

console.log(f3.sub())  //8

 

apply()方法和call()方法

聯繫我們

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