2012-08-04 50 views
1

我認爲他們是等價的,但我不知道:這兩種繼承策略有什麼區別?

var __extends = function(child, parent) { 
    for (var key in parent) { 
     if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    function ctor() { 
     this.constructor = child; 
    } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype; 
    return child; 
}; 

而且

var __extends = function(child, parent) { 
    for (var key in parent) { 
     if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    child.prototype = parent.prototype; 
    child.prototype.constructor = child; 
    child.__super__ = parent.prototype; 
    return child; 
}; 
+0

而你傳遞兩個函數? – Bergi 2012-08-04 01:36:30

回答

1

兩個功能延伸,以與parent對象的所有屬性的child(功能)對象,他們設置了__super__財產。然後差異開始:

function ctor() { 
    this.constructor = child; 
} 
ctor.prototype = parent.prototype; 
child.prototype = new ctor; 

此代碼爲childparent.prototype繼承創建一個原型對象。這是Object.create()所做的old version。這是傳統的JavaScript繼承模式。

child.prototype = parent.prototype; 
child.prototype.constructor = child; 
child.__super__ = parent.prototype; 

此代碼是廢話。它集child的原型對象parent.prototype,但就在現在這兩個屬性指向同一個對象(child.prototype === parent.prototype)下一行遺忘。因此,parent.prototype.constructor === childchild.__super__ === child.protoype - 呃。

+0

感謝您解決這個問題。具有很大的意義。 – 2012-08-04 02:35:01