How to refer to the correct this inside a callback?
POSSIBLE SOLUTION OF THE ABOVE PROBLEM
Step 1- TO KNOW ABOUT 'THIS'
A
function's this keyword behaves a little differently in JavaScript
compared to other languages. It also has some differences between strict
mode and non-strict mode.
function foo() { console.log(this); } // normal function call foo(); // `this` will refer to `window` // as object method var obj = {bar: foo}; obj.bar(); // `this` will refer to `obj` // as constructor function new foo(); // `this` will refer to an object that inherits from `foo.prototype`
Step 2 - TO REFER CORRECT 'THIS'
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => alert(this.data));
}
Step 3 - SET 'THIS' OF THE CALLBACK
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function MyConstructor(data, transport) { this.data = data; var boundFunction = (function() { // parenthesis are not necessary alert(this.data); // but might improve readability }).bind(this); // <- here we are calling `.bind()` transport.on('data', boundFunction); }
Step 4 - SET 'THIS' OF THE CALLBACK
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
array.map(callback[, thisArg])
var arr = [1, 2, 3]; var obj = {multiplier: 42}; var new_arr = arr.map(function(v) { return v * this.multiplier; }, obj); // <- here we are passing `obj` as second argument
0 comments:
Post a Comment