2014-05-02 24 views
0

我一直在用上述问题撞墙。比方说,我有下面的类:从构造函数返回一个数字

function Counter() {...} 

所以当我调用构造函数:

var c= new Counter(); 
console.log(c); //return 0 

而且如果我创建了以下方法:

Counter.prototype.increment = function() { 
return this += 1; 
}; 

应该增加1Ç每拨打一次电话

c.increment(); // return c=1 
c.increment(); // return c=2 

到目前为止,我想出了:

function Counter(){return Number(0)} 

但仍返回Number {}不是一个零...

有什么想法?

在此先感谢!

+0

为什么'console.log(c);'return 0? – Amberlamps

+0

它看起来像你想要一个对象,有时像一个普通数字的行为,有时就像包裹在一个对象中的数字。你试图用这个完成什么? – Guffa

+0

@Amberlamps它应该返回零 - 这就是我想要实现的.. – Altons

回答

0

由于您使用关键字new对其进行了实例化,因此无法从构造函数返回值,这会为您提供该对象的新实例。

商店的属性和增量,与其:

function Counter() { 
    this.count = 0; 
} 

Counter.prototype.increment = function() { 
    this.count++; 
    return this.count; 
}; 

var c= new Counter(); 

console.log(c.increment()); // 1 
console.log(c.increment()); // 2 
console.log(c.increment()); // 3 
+0

它确实实现了我所需要的 - 但是我怎样才能访问0?通过c.count? (c)在任何增量之前是不可能得到零的? – Altons

0

这是您的问题:

Counter.prototype.increment = function() { 
return this += 1; 
}; 

this是一个对象,+ =未对对象定义。

2

的JavaScript不允许自定义Object型直接模仿原始值。它也不允许为this分配一个新的值。

你必须,而不是存储值的属性中:

function Counter() { 
    this.value = 0; 
} 

var c = new Counter(); 
console.log(c);  // Counter { value: 0 } 

而且,从增加它的价值:

Counter.prototype.increment = function() { 
    this.value += 1; 
}; 

c.increment(); 
console.log(c.value); // 1 

虽然,你至少可以指定对象应该如何为什么`console.log(c);`return 0?要转换成原始的一个custom valueOf() method

Counter.prototype.valueOf = function() { 
    return this.value; 
}; 

console.log(c.value); // 1 
console.log(c + 2); // 3