0
var object = { _text: 'Hello World', getInvite: function() {return this._text}}; 
var func= object.getInvite; 
console.log(func());

Is it because here the function is being invoked not within the context of the object? Which makes 'this' undefined?

kohl
  • 566
  • 2
  • 9
  • 21
  • 1
    Try to put `()` at the end, id est, use func=object.getInvite(); – Eduardo Pascual Aseff Mar 10 '18 at 22:44
  • console.log(func) will give expected out as func variable is defined but func function – Naga Sai A Mar 10 '18 at 22:44
  • You need to bind `func` back to the original object before calling it, e.g. `func.bind(object)()` –  Mar 10 '18 at 22:49
  • This is not a duplicate my question is different @inostia – kohl Mar 10 '18 at 22:58
  • @amy can you explain the reason? – kohl Mar 10 '18 at 22:59
  • I believe the reason here is related to the behavior of 'this' in Javascript, I thought someone would mention that. Anyone? – kohl Mar 10 '18 at 23:00
  • Please stop duplicating this post, I asked for an explanation. Hope you people get it. – kohl Mar 10 '18 at 23:01
  • The first three answers in the linked question answers your question, if you care to read them. If your question is a duplicate, it's a duplicate. Whether you want an explanation isn't relevant. –  Mar 10 '18 at 23:03

1 Answers1

-1

It's because when you assign object.getInvite to func it loses reference to the rest of the "object" object.

object.getInvite() works because object has a property called _text while func is just a stand alone function which has no references to _text anymore.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
Proximo
  • 6,235
  • 11
  • 49
  • 67