What's the difference between two set of codes, I know what arrow function does but why traditional expression does not work?
Set - 1
loop through all elements
checkboxes.forEach( function (checkbox){
console.log(checkbox);
if( checkbox === this || checkbox === lastChecked)
{
inBetween = !inBetween;
console.log(" start checking them inbetween");
}
if(inBetween)
{
checkbox.checked = true;
}
});
Set - 2
loop through all elements
checkboxes.forEach(checkbox => {
console.log(checkbox);
if (checkbox === this || checkbox === lastChecked) {
inBetween = !inBetween;
console.log('Starting to check them in between!');
}
if (inBetween) {
checkbox.checked = true;
}
});
CodePudding user response:
Set - 1 is foreach with ES5 definition style whereas Set-2 is for ES6. Make sure the target/version supports ES5 so that Set-1 will work.
Also, you might wanna try replacing this with self in set-1 and defining self as this before the foreach or use bind
var self = this;
this.addNewObjects = function(arr){
arr.forEach(function(obj) {
self.addObject(new Obj(obj.prop1, obj.prop2));
});
}
or
this.addNewObjects = function(arr) {
arr.forEach(function(obj) {
this.addObject(new Obj(obj.prop1, obj.prop2));
}.bind(this));
}
CodePudding user response:
I think, may be u use this
in scope of forEach()
function, this is one of more different of two.
more explain is: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions