Ich habe eine Funktion, die ich für einen Konstruktoraufruf ...Warum wird die Eigenschaft meines Objekts in JavaScript nicht aktualisiert?
function Queue() {
if (!(this instanceof Queue)) return new Queue();
this.capacity = {};
this._count = 0;
}
Und diese Verfahren werden auf dem die Eigenschaft prototype Queue
... Alles koscher richtige Set vorbereitet haben?
Queue.prototype.enqueue = function(name, options) {
this.capacity[name] = options || {};
this.count();
if (this._count > 5) {
return 'Max capacity has been reached—which is five, please dequeue....'
}
};
Queue.prototype.count = function() {
var total = Object.keys(this.capacity);
total.forEach(function(elem) {
this._count++
});
if (this._count == 1) {
console.log(this.capacity[Object.keys(this.capacity)])
console.log('There is one item in the queue');
} else {
console.log(this.capacity[Object.keys(this.capacity)])
console.log('There are ' + this._count + ' items in the queue');
}
};
Meine Frage wie bekomme ich this._count
zu erhöhen, wenn die enqueue/Zählverfahren Feuer? Ich erhalte:
There are 0 items in the queue
Ich weiß, dass ich es auf dem .prototype
Eigenschaft hinzufügen könnte und legen Sie, dass in der Zählfunktion und haben eine lokale var Referenz ...
Queue.prototype.count = function() {
var total = Object.keys(this.capacity), count = 0;
total.forEach(function(elem) {
this.count++
});
Queue.prototype.call = Ruf // < - komisch nein?
if (this.count == 1) {
console.log(this.capacity[Object.keys(this.capacity)])
console.log('There is one item in the queue');
} else {
console.log(this.capacity[Object.keys(this.capacity)])
console.log('There are ' + this.count + ' items in the queue');
}
};
Aber das scheint nicht elegant zu sein ...
Vielen Dank im Voraus!
Sie könnten zu 'this._count + = Object.keys (thiscapacity) .length' vereinfachen. Und meinst du nicht, '_count' auf null zurückzusetzen oder' '' anstelle von '+ =' zu benutzen? –