Domanda

I've been my banging head against the wall with the above question. Let's say I have the following class:

function Counter() {...}

so when I call the constructor:

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

furthermore If I created the following method:

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

it should increment c by 1 for every call

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

so far I have come up with:

function Counter(){return Number(0)}

but still returns Number{} not a zero...

Any thoughts?

Thanks in advance!

È stato utile?

Soluzione 2

You can't return a value from the constructor because you instantiate it using the new keyword, this gives you a new instance of the object.

Store a property and increment that instead:

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

Altri suggerimenti

JavaScript doesn't allow for a custom Object type to directly imitate a primitive value. It also doesn't allow this to be assigned a new value.

You'll have to instead store the value within a property:

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

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

And, increment the value from it:

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

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

Though, you can at least specify how the object should be converted to a primitive with a custom valueOf() method:

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

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

This is your problem:

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

this is an object, += is not defined for objects.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top