国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

一個(gè)JavaScript繼承的實(shí)現(xiàn)

2019-11-21 02:29:33
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(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;

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沙田区| 瓮安县| 平舆县| 钦州市| 武陟县| 大田县| 禹州市| 北碚区| 昌江| 井研县| 邳州市| 镇原县| 玉屏| 柳河县| 卓资县| 固阳县| 女性| 北碚区| 瑞金市| 会同县| 雷州市| 拉萨市| 修水县| 庄浪县| 萝北县| 筠连县| 彩票| 甘德县| 肥乡县| 扬中市| 夏邑县| 林甸县| 杭州市| 乌拉特前旗| 汪清县| 达日县| 广丰县| 错那县| 包头市| 包头市| 大兴区|