传统观点认为,要在Javascript中模拟OOP,我们会在功能和原型方面做所有事情:
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();
};
答案 0 :(得分:3)
new foo();
这是一个实例,而不是一个类。
要创建派生类,您需要创建一个新函数,从其内部调用基本ctor,然后将新函数的prototype
设置为从基础prototype
创建的对象:< / p>
function Derived() {
Base.call(this);
}
Derived.prototype = Object.create(Base.prototype);
有关详细信息以及更长,更正确的实现,请参阅我的blog post。