I got a definition that looks like so:
function className(data)
{
this.dataRecords = [];
$.each(data, function(key, item)
{
this.dataRecords.push(new dataRecord(item.record));
}
}
But for some reason js does not think this.dataRecords is actually an array. I modified the code to do the following:
function className(data)
{
var array = [];
$.each(data, function(key, item)
{
array.push(new dataRecord(item.record));
}
this.dataRecords = array;
}
This works fine, but i'd rather push the data to the actual object, in stead of now having to do another this.dataRecords = array;
to get the job done. I want to give the class functions for manipulating this.dataRecords from my class's perspective( like addRecord and removeRecord), which with this technique, becomes a little tedious.
Is there any way I can make js recognize the array(this.dataRecords) as an array?
Because inside the callback of each
, this
refers to the item from the array.
FIX1:
Store the value of this before entering each
:
function className(data) {
this.dataRecords = [];
var that = this; // that is this
$.each(data, function(key, item) {
that.dataRecords.push(new dataRecord(item.record));
// ^^^^ use that instead of this
});
}
FIX2:
Use arrow functions, because they don't get bound to any this
(they don't have a this
so the only this
is your class):
function className(data) {
this.dataRecords = [];
$.each(data, (key, item) => {
this.dataRecords.push(new dataRecord(item.record));
});
}
FIX3:
bind the callback of each
to your class using Function.prototype.bind
:
function className(data) {
this.dataRecords = [];
$.each(data, function(key, item) {
this.dataRecords.push(new dataRecord(item.record));
}.bind(this));
}
when bind
is called on a function, the return value will be another function that has its this
value always set to the parameter of bind
. So, in the above we define a function that accepts two arguments (key, item)
, and then we bind it to this
(this
in this case is the instance of the class as we are still in the scope of the constructor), and we pass the returned value of bind
(which is a new function similar to the original one except it has its this
set to the instance of the class) to each
.