这段javascript继承的代码有什么问题?

时间:2012-10-09 09:34:02

标签: javascript oop inheritance

function condition(){ 
  this.expression = ""; 
  this.toString = function(){
    return this.expression;
  }
};

function and(first, second){
    this.expression = first + " and " + second;
}

function nop(){};
nop.prototype = condition.prototype;

and.prototype = new nop();

var a =new and(1,2);

console.log(a.toString());

预计会看到" 1和2"作为输出,但这是发生的事情: " [对象]"

5 个答案:

答案 0 :(得分:1)

您正在将condition的原型转移到nop的原型。问题是你的condition.toString未在原型中声明......在这里:

function condition(){ 
  this.expression = ""; 

};
  condition.prototype.toString = function(){
    return this.expression;
  }
function and(first, second){
    this.expression = first + " and " + second;
}

function nop(){};
nop.prototype = condition.prototype;

and.prototype = new nop();

var a =new and(1,2);

console.log(a.toString());

OR

function condition(){ 
  this.expression = ""; 
  this.toString = function(){
    return this.expression;
  }
};

function and(first, second){
    this.expression = first + " and " + second;
}

function nop(){};
nop = condition;

and.prototype = new nop();

var a =new and(1,2);

console.log(a.toString());

答案 1 :(得分:1)

你没有覆盖toString方法,因为从不调用条件的构造函数!试着这样做;

condition.prototype.toString=function(){
    return this.expression;
}

答案 2 :(得分:0)

尝试将字符串传递给您的函数,就像您尝试将整数连接到字符串var a =new and("1","2");

时一样

答案 3 :(得分:0)

应该是这样的

function condition(){ 
  this.expression = ""; 
};    

condition.prototype.toString = function(){
   return this.expression;
}

答案 4 :(得分:0)

好的,所以这里的问题是你将伪经典的两种继承模式(http://davidshariff.com/blog/javascript-inheritance-patterns/)与功能模式混合在一起。

您可以通过在构造函数上添加方法来创建对象:

function MyClass() {
    var privateProperty = 1;
    this.publicProperty = 2;

    function pivateMethod() {
        // some code ...
    }

    this.publicMethod = function() {
        // some code ...
    };
}

// inheritance
function SubClass() {
    MyClass.call(this);

    this.newMethod = function() { };
}

在此创建此类的实例时,您将再次创建每个方法。

然后你有原型模式:

function MyClass() {
    this._protectedProperty = 1;
    this.publicProperty = 2;
}
MyClass.prototype._protectedMethod = function() {
    // some code ...
};
MyClass.prototype.publicMethod = function() {
    // some code ...
};

// inheritance
function SubClass() {
    MyClass.call(this);
}
SubClass.prototype = new MyClass();
SubClass.prototype.newMethod = function() { };

// OR
function SubClass() {
    MyClass.call(this);
}

function dummy() { }
dummy.prototype = MyClass.prototype;
SubClass.prototype = new dummy();
SubClass.prototype.newMethod = function() { };

你必须选择这两种模式中的一种,而不是两种模式。

我已经在这个小提琴上修改了你的代码:http://jsfiddle.net/dz6Ch/