以上问题一直困扰着我。假设我有以下课程:

function Counter() {...}


所以当我调用构造函数时:

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


此外,如果我创建了以下方法:

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


每次通话都应将c加1

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


到目前为止,我想出了:

function Counter(){return Number(0)}


但仍返回Number {}而不是零...

有什么想法吗?

提前致谢!

最佳答案

您不能从构造函数返回值,因为使用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

关于javascript - 从构造函数返回数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23434647/

10-12 15:59