DR01D
DR01D

Reputation: 1365

.call method throws error at this keyword

In the simplified code below I attempt to push the string goblin into the creatures array. Unfortunately I get an error at this.push(x).
Uncaught TypeError: Cannot read property 'push' of undefined at addName

If this points to the object that owns it, shouldn't that be the creatures object when it is used with a call statement? Thanks so much for any help!

'use strict';
	
var creatures;
	
creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x) {
  this.push(x)
}

addName('goblin').call(creatures);

Upvotes: 1

Views: 35

Answers (3)

Lakshitha Ruwan
Lakshitha Ruwan

Reputation: 959

Classes suites better in this situation I believe

    'use strict';

class Creatures5{
    constructor(){
        this.creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];
    }   


    addName(x) {
      this.creatures.push(x)
        console.log(this.creatures)
    }
}
var CreatureObj = new Creatures5;
CreatureObj.addName('goblin');

OR you can

'use strict';
var creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x){
    creatures.push(x)
}


this.addName.call('goblin')

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

There are two problems in your code

  • Invoking call method on undefined - You are invoking call method to the return value of addName method call which returns undefined while call can be invoked only on function.
  • call method takes this argument as the first parameter and arguments to the function to be invoked from the second parameter onward.

You need to pass goblin as the second parameter of call

 addName.call(creatures, 'goblin');

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68655

You need to call like addName.call(creatures). Call the call function on the function itself, not on its result, which you have done. And if your function takes parameters, you can pass those parameters after passing the context.

'use strict';
	
var creatures;
	
creatures = ['zombie', 'skeleton', 'orc', 'giant spider'];

function addName(x) {
  this.push(x)
}

addName.call(creatures, 'goblin');

console.log(creatures);

Upvotes: 2

Related Questions