prototype 和 length
函數(shù)的屬性和方法
ECMAScript 中函數(shù)是對(duì)象,因此也有屬性和方法。每個(gè)函數(shù)都有兩個(gè)屬性,length 和 prototype 其中l(wèi)ength 表示希望接收的命名函數(shù)參數(shù)的個(gè)數(shù)。
length 屬性
下面的代碼就是說(shuō)的 length 屬性,比較簡(jiǎn)單,沒(méi)啥好說(shuō)的。
function box(a,b,c){
return d=(a+b)/c;
}
box(1,2,3);
document.write(d+"<br/>");
document.write(box.length+"<br/>");

prototype 屬性
然后我們看看 prototype 屬性。
對(duì)于 prototype 的理解下面的例子覺(jué)得很不錯(cuò)。
提問(wèn):對(duì)于下面的代碼有
function a(){this.name="你好";this.age="25";}
a.prototype.b=function (){alert("hello world")};
上面代碼的意思是不是說(shuō):在a函數(shù)的對(duì)象原型(也就是對(duì)象Object)上添加一個(gè)b()方法呢,這樣子a函數(shù)就可以繼承了??也就是說(shuō)可以用這樣的一段代碼代替
a.b=function(){alert("hello world")}
回答:這樣語(yǔ)法是沒(méi)有錯(cuò)誤的。a.b = function(){...}是可以的,但是這樣的話,如果有一百個(gè)a”對(duì)象“,那么你的100個(gè)a上面就有100個(gè)b方法??墒牵闳绻谠蜕显O(shè)置b方法,那么這100個(gè)a都只共享著一個(gè)b方法,這樣一來(lái)可以節(jié)省內(nèi)存,二來(lái)更具有”面向?qū)ο蟆钡臐撡|(zhì)。
而 prototype 有兩個(gè)方法, apply 和 call 。
二者的區(qū)別: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
看看下面的例子:
function cat(){
}
cat.prototype={
food:"fish",
say: function(){
alert("I love "+this.food);
}
}
var blackCat = new cat;
blackCat.say();

但是如果我們有一個(gè)對(duì)象 Dog = {this.food="bone"},我們不想對(duì)它重新定義 say 方法,那么我們可以通過(guò) call 或 apply 用 blackCat 的 say 方法:
function cat(){
}
cat.prototype={
food:"fish",
say: function(){
document.write("I love "+this.food+"<br/>"+"<br/>");
}
}
var blackCat = new cat;
blackCat.say();
var yellowCat= new cat;
yellowCat.say();
function Dog(){
this.food="bone";
}
var dog = new Dog();
blackCat.say.call(dog);

所以,可以看出 call和 apply 是為了動(dòng)態(tài)改變 this 而出現(xiàn)的,當(dāng)一個(gè) object 沒(méi)有某個(gè)方法,但是其他的有,我們可以借助 call 或 apply 用其它對(duì)象的方法來(lái)操作。