2017-09-05 65 views
0

我對JavaScript的原型繼承有很好的理解,但我不會說它是完美的。我正在查看JavaScript繼承的最新原型語法,到目前爲止,這非常合理。爲什麼代理類需要JavaScript ES5原型繼承?

__proto__用於查找父功能的prototype。說我有CatMammal,我可以簡單地指向Cat.prototype.__proto__Mammal.prototype

ChildClass.prototype.__proto__ = ParentClass.prototype; 
ChildClass.prototype.constructor = ChildClass; 

使用__proto__強烈不鼓勵,因爲它只是直到最近才被標準化。因此,現代標準化的做法是使用Object.create

ChildClass.prototype = Object.create(ParentClass.prototype); 
ChildClass.prototype.constructor = ChildClass; 

現在讓我們來看看ES5的替代方法

function Surrogate() {}; 
Surrogate.prototype = ParentClass.prototype; 
ChildClass.prototype = new Surrogate(); 
ChildClass.prototype.constructor = ChildClass; 

顯然,

ChildClass.prototype = ParentClass.prototype; 

是不好的,因爲修改ChildClass的原型也將修改ParentClass的原型。

但爲什麼我們不能做到這一點?

ChildClass.prototype = new ParentClass(); 

爲什麼我們需要在兩者之間的替代?

+2

個人而言,我會說你'ES5的代理approach'並不完全準確。 'Object.create'在2011年被添加到'5.1'中,所以現在的JS在很長的一段時間內都是如此。 – loganfsmyth

+0

在ES5引入Object.create之前使用'new'。 – Bergi

回答

1

但爲什麼我們不能這樣做呢?

ChildClass.prototype = new ParentClass();

你怎麼知道調用ParentClass構造W/O參數就不會拋出一個錯誤?

想象一下ParentClass是這樣實現的。

function ParentClass(name) { 
    if(!name) throw new Error('name is required'); 

    this.name = name; 
} 
+0

啊啊謝謝,好點!這是做代理班的唯一原因嗎?是否還有其他隱藏的警告我應該知道,並且代理技巧旨在抓住? – cfeng

+0

@cfeng任何其他副作用'ParentClass'都可以。例如,它可能會調用外部API,增量計數器等。 –

+1

@cfeng我們根本不想調用構造函數。它應該初始化什麼?沒有實例。 – Bergi