0

let user = {
  firstName: 'Testname'
}

function testAlert() {
  alert(this.firstName);
}
let funcUser = testAlert.call(user); // Testname
funcUser();

Shows error in console:

Uncaught TypeError: funcUser is not a function

I am not getting why it is showing error.

Thanks

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • 7
    Maybe you meant `bind` there? – choz Jun 23 '20 at 19:24
  • 5
    [`call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) will actually call the function. So you aren't assigning `funcUser` the function reference, you're assigning it the return value (`undefined`). – Brian Thompson Jun 23 '20 at 19:25

2 Answers2

1

Call and apply will run your function, bind just assign context. In your example you should use bind instead of call.

0

instead of .call use .bind

let user = {
    firstName: 'Testname'
}

function testAlert(){
    alert(this.firstName);
}

let funcUser =  testAlert.bind(user);  // Testname
funcUser();

or you can return a function from the testAlert()

example

let user = {
    firstName: 'Testname'
}

function testAlert(){
   return function() { alert(this.firstName) }
}

let funcUser = testAlert.call(user);  // Testname

funcUser()
Marik Ishtar
  • 2,899
  • 1
  • 13
  • 27