我可以在javascript中覆盖构造函数吗?

时间:2012-11-14 21:31:43

标签: javascript

我刚刚在Javascript类中了解到了can overwrite a method,如下所示,但是实际的构造函数呢?

如果可能,如何在不实例化课程的情况下进行操作?

var UserModel = (function() {
  var User;
  User = function() {}; // <- I want to overwrite this whilst keeping below methods
  User.prototype.isValid = function() {};
  return User;
})();

2 个答案:

答案 0 :(得分:9)

暂时保存prototype对象,然后替换构造函数:

var proto = UserModel.prototype;
UserModel = function () { /* new implementation */ };
UserModel.prototype = proto;

答案 1 :(得分:0)

基本上,你创建一个什么都不做的临时函数,你设置它的原型有父类的原型,那么你可以使用基类作为父类而不调用它的构造函数。

如果需要从子类的构造函数引用父类的构造函数,则juste必须使用Function.prototype.apply来转发构造函数调用。

Javascript继承模型:

// Base class

var Base = function ( ) {
    this.foo = 40;
};

Base.prototype.bar = function ( ) {
    return this.foo;
};

// Inherited class

var Child = function ( ) {
    Base.apply( this, arguments );
    this.foo += 2;
};

var F = function ( ) { };
F.prototype = Base.prototype;
Child.prototype = new F( );