1

My way of binding not working. please correct me.

const ob = {
  name:'arif',
  getName:() => {
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); //return the global name!!
user2024080
  • 1
  • 14
  • 56
  • 96

2 Answers2

2

Note:- Here even without binding your function will be taking this as ob only if you call it directly on object.

Arrow function do not have this, normal function do have

const ob = {
  name:'arif',
  getName: function(){
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); 
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

The Arrow function doesn't have an argument property of its own, the bind will fail with Arrow function.

instead, you can use normal function here:

 const ob = {
  name:'arif',
  getName: function() {
    console.log(this)
    return this.name; 
  }
}
const x = ob.getName.bind(ob);
console.log(x()); //returns the object name !!