call()和apply()的認知

來源:互聯網
上載者:User

標籤:

  •  apply:方法能劫持另外一個對象的方法,繼承另外一個對象的屬性.

   Function.apply(obj,args)方法能接收兩個參數  

  obj:這個對象將代替Function類裡this對象  

  args:這個是數組,它將作為參數傳給Function(args-->arguments)

  Function.call(obj,[param1[,param2[,…[,paramN]]]])  

  obj:這個對象將代替Function類裡this對象  

  params:這個是一個參數列表

  

1.apply樣本:  

<script type="text/javascript">   

/*定義一個人類*/   

function Person(name,age) {   

this.name=name; this.age=age;   

}   

/*定義一個學生類*/   

functionStudent(name,age,grade) {   

    Person.apply(this,arguments); this.grade=grade;   

}   

//建立一個學生類   

var student=new Student("qian",21,"一年級");   

//測試   

alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);   

//大家可以看到測試結果name:qian age:21 grade:一年級   

//學生類裡面我沒有給name和age屬性賦值啊,為什麼又存在這兩個屬性的值呢,這個就是apply的神奇之處.   

</script>   

分析: Person.apply(this,arguments);  

this:在建立對象在這個時候代表的是student  

arguments:是一個數組,也就是[“qian”,”21”,”一年級”];  

也就是通俗一點講就是:用student去執行Person這個類裡面的內容,在Person這個類裡面存在this.name等之類的語句,這樣就將屬性建立到了student對象裡面  

2.call樣本  

在Studen函數裡面可以將apply中修改成如下:  

Person.call(this,name,age);  

這樣就ok了

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.