2014-09-28 71 views
0

传统观念认为在JavaScript中模拟OOP,我们的职能和原型方面做的一切:在Javascript中定义构造函数派生类

var fooObject = function() { 
    //Variables should be defined in the constructor function itself, 
    //rather than the prototype so that each object will have its own variables 

    this.someProperty = 5; //Default value 
}; 

//Functions should be defined on the prototype chain so that each object does not 
//have its own, separate function methods attached to it for performing the same 
//tasks. 

fooObject.prototype.doFoo = function() { 
    //Foo 
} 

现在,创建一个派生类,我们这样做:

var derivedFromFoo = new foo(); 

但是如果我们想要做一些其他的东西在我们的构造函数派生的对象会发生什么?像设置其他属性?我们可以这样做

var derivedFromFoo = function() { 
    this = new foo(); 
}; 
+1

FWIW,你永远不能指定'this'。 – 2014-09-28 02:45:16

回答

3
new foo(); 

这是一个实例,而不是一类。

要创建一个派生类中,你需要一个新的功能,从它里面调用基构造函数,然后将新功能的prototype从基地prototype创建的对象:

function Derived() { 
    Base.call(this); 
} 
Derived.prototype = Object.create(Base.prototype); 

对于更多细节以及更长,更正确的实现,请参阅我的blog post

+0

+1(调用(this))调用“超类”构造函数 – Tap 2014-09-28 02:13:05

相关问题