This
Bind vs Apply vs Call
function test(a, b) {
console.log(this + a + b);
}
var array = [1, 2];
var object = {
id: 1,
};
test(1, 2);
// result : window object 1 2 ,since this means the window at the beginning if it is not defined
test.call(object, 1, 2);
//result: {id:1} 1 2 ,since object is put into function , so this refer to object
test.apply(object, array);
//result: {id:1} 1 2 ,basically same as call, but it is allowed only 2 arguments and second argument must be a array
var test2 = test.bind(object);
test2(1, 2);
//result: {id:1} 1 2 ,basically same as call, but the syntax is different
Arrow Function vs Normal Function
const test = {
a:1,
fn: function(){
console.log(this.a);
},
fn2: ()=>{
console.log(this.a);
},
fn3: function(){
return () => {
console.log(this.a);
}
},
fn4(): function(){
let a= 10;
return function(){
console.log(this.a);
}
},
}
test.fn();
// 1
test.fn2();
// undefined
test.fn3()();
// 1
test.fn4()();
// undefined
This of normal function refer to its parent
This of arrow function inherit this, but without defining the new this meaning
Last updated
Was this helpful?