0

I have the following code below which is an object literal with two functions and one property.

My problem is that when function greetSomeone gets called, it's context is not person, but an event (eg jQuery or DOM event), therefore the context changes to the event that was fired and this.getName is not found.

So, how do I call this.getName() inside greetSomeone to execute correctly?

I tried getName.call(person) but it did not work.

var person = {
  name: 'john',
  greetSomeone: function(event) {
    //i tried getName.call(person) but doesn't work
    return 'hello i am ' + this.getName() //<---this doesn't work
  },
  getName: function() {
    return this.name
  }
};
console.log(person.greetSomeone()) // works here, but not in an event handler
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
user3092075
  • 281
  • 1
  • 2
  • 9
  • `ANYTHING.greetSomeone.call(person)` – Rayon May 02 '17 at 12:47
  • The result is `hello i am john`. Is it supposed to be the right output? – kind user May 02 '17 at 12:48
  • 2
    The code you've posted isn't the source of the problem, rather it's at the point you're attaching it to an event handler. Can you include that part, so the best fix can be suggested? – James Thorpe May 02 '17 at 12:49
  • @Kinduser — As mentioned by OP, context is different that what he has mentioned in `console` – Rayon May 02 '17 at 12:49
  • 4
    The code you posted would work. Your problem is happening when you pass `person.greetSomeone` to some other function for use as a callback, and the solution is to pass `person.greetSomeone.bind(person)` instead. – Pointy May 02 '17 at 12:49
  • 2
    getName.call(person) works as well – Nitesh Rana May 02 '17 at 12:51
  • https://jsfiddle.net/rayon_1990/qdgb6o9g/ – Rayon May 02 '17 at 12:53
  • `getName.call(person)` will only work so long as you're treating your classes as static. Presumably, because name is a property of person and it doesn't look like it's supposed to be static, I assume it can be modified. Just using `getName.call(person)` will always use the default for the name property. What needs to be in place is an `attachEvents` method I think. If you make that a method of the object, you can bind the correct instance of the object there. – Joseph Marikle May 02 '17 at 13:05
  • @Pointy is correct soln. OP needs to implement as Pointy suggested – NiRUS May 02 '17 at 13:11

0 Answers0