2013-01-02 49 views
1

我试图在Javascript中更好地理解OOP。有人可以解释下面的例子中如何使用create方法和替代方法吗?我在网上查了一下,查看了几篇关于SO的文章,但仍然没有掌握下面代码中发生的事情。我提供了评论来说明我的理解。请纠正我错在哪里。了解Javascript构造函数:自定义创建方法

这个例子是用来覆盖从基类的方法:

// Defines an Employee Class 
function Employee() {} 

// Adds a PayEmployee method to Employee 
Employee.prototype.PayEmployee = function() { 
    alert('Hi there!'); 
} 

// Defines a Consultant Class and 
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why 
// I believe this is a way to inherit from Employee? 
function Consultant() { 
    Employee.call(this); 
} 

// Assigns the Consultant Class its own Constructor for future use -- not sure 
Consultant.prototype.constructor = Consultant.create; 

// Overrides the PayEmployee method for future use of Consultant Class 
Consultant.prototype.PayEmployee = function() { 
    alert('Pay Consultant'); 
} 
+2

老板,哪里还有我的薪水是多少? 〜''你好!':'P' –

+4

'Object.create'在该代码中根本没有被使用。 –

+0

和'Consultant.create'不存在。 @ T.J .:你解释了这一千次,你肯定找到最好的重复;) –

回答

4

此代码:

function Consultant() { 
    Employee.call(this); 
} 

正在调用的Employee构造顾问构造函数被调用时(即,当一个顾问实例创建)。如果Employee构造函数正在进行任何初始化,那么在创建Consultant“子类型”时调用它会很重要。

此代码:

Consultant.prototype.constructor = Consultant.create; 

有点的谜。这意味着有一个名为create的函数,它是Consultant函数对象的一个​​属性。但是,在您发布的代码示例中,没有此类属性。实际上,这条线将undefined分配给顾问构造函数。

你的问题不问,只是仅供参考,我认为你可能想这条线的代替与创造功能,是这样的:

Consultant.prototype = new Employee(); 
Consultant.prototype.constructor = Consultant; 

这就是原型继承模式。这当然不是唯一或必然的最佳方法,但我喜欢它。

更新

如果员工需要一个参数,你可以处理像这样:

// Employee constructor 
function Employee(name) { 
    // Note, name might be undefined. Don't assume otherwise. 
    this.name = name; 
} 

// Consultant constructor 
function Consultant(name) { 
    Employee.call(this, name); 
} 

// Consultant inherits all of the Employee object's methods. 
Consultant.prototype = new Employee(); 
Consultant.prototype.constructor = Consultant; 
+3

请不要'Consultant.prototype = new Employee();'。只要'员工'不期待任何争论,这就行得通了。但如果它呢?在这个阶段,你并不是真的想要调用构造函数(稍后在子构造函数中这样做),你只是想将原型放入链中。这可以通过'Object.create'轻松完成:'Consultant.prototype = Object.create(Employee.prototype)'。 –

+0

'Consultant.prototype = new Employee();'是原型继承模式的重要组成部分。它确保了每当你做新的Consultant()(有或没有参数)时,新的Consultant对象将拥有Employee对象在新'Employee()'时所拥有的所有方法。请注意,使用此模式的一个缺点是,如果“基本”构造函数Employee带有参数,则它必须能够在没有参数传递时处理该情况。 – dgvid

+1

也许我没有明确表达自己:为了避免这个缺点,你应该使用Object.create代替。为了确保一个新的Consultant对象被正确初始化,你可以在Consultant构造函数中调用Employee的构造函数。就这样。正如我所说的,在那个时候,你不想创建一个'Employee'实例,你只是想把它的原型放到原型链中。 'Object.create'可以让你在不初始化一个新的'Employee'对象的情况下做到这一点。 –

相关问题