I'm mencoba untuk menggunakan metode callback addToCount
bukan anonymous function di forEach
. Tapi aku bisa't access ini.count
di dalamnya (kembali undefined
).
function Words(sentence) {
this.sentence = sentence;
this.count = {};
this.countWords();
}
Words.prototype = {
countWords: function() {
var words = this.sentence.split(/\W+/);
words.forEach(this.addToCount);
},
addToCount: function(word) {
word = word.toLowerCase();
if (word == '') return;
if (word in this.count)
this.count[word] += 1;
else
this.count[word] = 1;
}
}
Saya pikir masalahnya adalah ruang lingkup. Bagaimana saya bisa lulus ini
untuk addToCount
atau apakah ada cara lain untuk membuatnya bekerja?
Anda perlu menggunakan Fungsi#mengikat
untuk mengikat lingkup:
words.forEach(this.addToCount.bind(this));
Catatan bahwa ini tidak tersedia di semua browser: anda harus menggunakan shim (seperti yang disediakan di link di atas) untuk menambahkannya di browser yang don't dukungan Fungsi#bind
.
Sebagai dandavis poin di komentar, anda dapat melewati nilai Array#forEach
sebagai konteks untuk callback:
words.forEach(this.addToCount, this);
Mencoba sesuatu seperti ini. I've digunakan yang
daripada _this
tapi juga saya've pindah addToCount
sehingga's dalam countWords
. Bahwa ternyata countWords
menjadi penutupan yang mengandung itu.
Words.prototype = {
countWords: function() {
var that = this, words = this.sentence.split(/\W+/);
words.forEach(function(word) {
word = word.toLowerCase();
if (word == '') return;
if (word in that.count)
that.count[word] += 1;
else
that.count[word] = 1;
});
}
}