一個(gè)JavaScript繼承的實(shí)現(xiàn)
2019-11-21 02:29:33
供稿:網(wǎng)友
Author:尹偉銘
Blog:http://my.donews.com/yinwm/
如我前面的文章說(shuō)的,對(duì)于JavaScript,一個(gè)類,就是一個(gè)function,他的類方法(也就是static的)都是作為這個(gè)function的一部分,而實(shí)例方法,都是在prototype上面的。
function ClassA() {
}
ClassA.staticMethod = function () {
}
ClassA.prototype.instanceMethod = function () {
}
在我這個(gè)實(shí)現(xiàn)當(dāng)中,一個(gè)類的繼承是拷貝父類的所有類方法,這樣子類就有了父類的靜態(tài)方法。
然后讓子類的prototype.prototype指向父類的prototype.
然后可以根據(jù)自己的需要,重寫一些方法。
function ClassB() {
}
ClassB.staticMethod = ClassA.staticMethod;
ClassB.prototype.prototype = ClassA.prototype;
ClassB.prototype.instanceMethod = function () {
// method 2
}
對(duì)于子類,使用一個(gè)prototype的鏈,來(lái)實(shí)現(xiàn)方法的實(shí)例方法的繼承。之所以選擇這種實(shí)現(xiàn)方法,是因?yàn)樽宇愂且貙懫渲械哪承┓椒ǖ摹6鴓rototype又是一個(gè)reference,所以直接的寫作ClassB.prototype = ClassA.prototype,會(huì)在重寫ClassB的實(shí)例方法的同時(shí),破壞ClassA的實(shí)例方法。而修改后的方法則會(huì)屏蔽父類的。
尋找方法的順序是,instanceA.prototype.method -> ClassA.prototype.
此時(shí)對(duì)于類方法的繼承,已經(jīng)實(shí)現(xiàn),現(xiàn)在需要實(shí)現(xiàn)在子類中,調(diào)用父類的方法。
對(duì)于Java,這樣的使用是很平常的
public void method() {
super.method();
}
在JavsScript中,為了實(shí)現(xiàn)此類功能,所以必須保留一個(gè)parent的reference,指向ParentClass.prototype.
ClassB.prototype.parent = ClassA.prototype.
那么在instanceB里面調(diào)用this.parent.method.call(this);就可以使用父類的方法了。使用call調(diào)用,是為了把自己的數(shù)據(jù)傳到父類。更漂亮的解決方法,我還沒有想到。
所以完成的代碼是
function ClassA() {
}
ClassA.prototype.method1 = function () {
}
ClassA.staticMethod = function () {
}
function ClassB(){
}
ClassB.staticMethod = ClassA.staticMethod;
ClassB.prototype.prototype = ClassB.prototype.parent = ClassA.prototype;
這個(gè)我抽象出來(lái)一個(gè)extend方法,
var LCore = function () {
}
LCore.extend = function (destination, source) {
// copy all functons
for (var prop in source) {
if (prop == “prototype”) {
continue;
}
destination.prototype[prop] = source[prop];
}
// make a reference for parent and reference prototype
destination.prototype.prototype = destination.prototype.parent = source.prototype;
return destination;
}