1
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”作为输出,但这就是发生的事情:“[object Object]”

4

5 回答 5

1

你没有覆盖 toString 方法,因为条件的构造函数永远不会被调用!尝试这样做;

condition.prototype.toString=function(){
    return this.expression;
}
于 2012-10-09T09:43:00.503 回答
1

您正在将原型转移conditionnop的原型。问题是你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());

或者

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());
于 2012-10-09T09:40:52.860 回答
0

尝试将字符串传递给您的 and 函数,因为此时您正试图将整数连接到字符串 var a =new and("1","2");

于 2012-10-09T09:40:52.407 回答
0

应该是这样的

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

condition.prototype.toString = function(){
   return this.expression;
}
于 2012-10-09T09:41:11.263 回答
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/

于 2012-10-09T09:47:07.453 回答