1. 前言
為什麼將這三個概念放在一起說。原因是這些是會在實現js 繼承會需要使用到的
2. call 和 apply
call 和 apply 的作用基本類似, 都是去執行function並將這個function 的context替換成第一個參數帶入。 兩者的不同是call 必須將function 的參數一一帶入,而 apply 只要在第二個參數帶入一個數列。
function fn( arg1, arg2,... ){ // do something}fn( arg1, arg2,... );fn.call( context, arg1, arg2,... );fn.apply( context, [ arg1, arg2,... ]);
手冊的解釋:
===================================
call 方法
調用一個對象的一個方法,以另一個對象替換當前對象。
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
參數
thisObj
可選項。將被用作當前對象的對象。
arg1, arg2, , argN
可選項。將被傳遞方法參數序列。
說明
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。
如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。
=====================================
<!--by oscar999 2013-1-17--> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><script>var func=new function(){this.a="func"} var newfunc=function(x){ var a="newfunc"; alert(this.a); alert(x); } newfunc.call(func,"inputParameter1"); /*alert are * func/inputParameter1; not newfunc/inputParameter1 */</script></body></html>
從以上的例子可以看出, alert(this.a), 返回的是並不是當前函數裡的值。
使用call 執行的速度會稍微快一些, 不過差異不大。
3.prototype
JavaScript沒有"子類"和"父類"的概念,也沒有"類"(class)和"執行個體"(instance)的區分,全靠一種很奇特的"原型鏈"(prototype chain)模式,來實現繼承。
prototype 其實就是建構函式的一個屬性。
所有執行個體對象需要共用的屬性和方法,都放在這個對象裡面;那些不需要共用的屬性和方法,就放在建構函式裡面。
執行個體對象一旦建立,將自動引用prototype對象的屬性和方法。也就是說,執行個體對象的屬性和方法,分成兩種,一種是本地的,另一種是引用的。
function Person(name){this.name = name;this.gender = "male";}var person1 = new Person("MM");var person2 = new Person("YY");person1.gender = "female";alert(person2.gender);// male</script>
<script>function Person(name){this.name = name;}Person.prototype.gender = "female";var person1 = new Person("MM");var person2 = new Person("YY");alert(person2.gender);// male</script>
比較以上兩個例子就知道了。
4. 參考
http://www.ruanyifeng.com/blog/2011/06/designing_ideas_of_inheritance_mechanism_in_javascript.html