關于對象的繼承,一般的做法是用復制法: Object.extend
見protpotype.js 的實現方法:
代碼如下:Object.extend = function(destination, source) {
for (property in source) {
destination[property] = source[property];
}
return destination;
}
除此以外,還有一種不太常見的方法: Function.apply.
apply 方法能劫持(<<Ajax in Action>> 書中用到"劫持"一語,很生動啊)另外一個對象的方法,
繼承另外一個對象的屬性。
示范代碼如下:
Apply示范代碼
代碼如下:<script>
function Person(name,age){ //定義一個類,人類
this.name=name //名字
this.age=age //年齡
this.sayhello=function(){alert("hello")}
}
function Print(){ //顯示類的屬性
this.funcName="Print"
this.show=function(){
var msg=[]
for(var key in this){
if (typeof(this[key])!="function") msg.push([key,":",this[key]].join(""))
}
alert(msg.join("/n"))
}
}
function Student(name,age,grade,school){ //學生類
Person.apply(this,arguments)
Print.apply(this,arguments)
this.grade=grade //年級
this.school=school //學校
}
var p1=new Person("jake",10)
p1.sayhello()
var s1=new Student("tom",13,6,"清華小學")
s1.show()
s1.sayhello()
alert(s1.funcName)
</script> 學生類本來不具備任何方法,但是在 Person.apply(this,arguments) 后,他就具備了 Person類的sayhello方法和
所有屬性。 在 Print.apply(this,arguments) 后就自動得到了 show() 方法。