0

Im new to javascript. I want to ask you. I have this code:

var fullname = 'David'; 
var obj = {
  fullname: 'Jhon', 
  prop: { 
    fullname: 'Angle', 
    getFullname: function () { 
      return this.fullname; 
    } 
  } 
}; 
console.log(obj.prop.getFullname()); 
var test = obj.prop.getFullname; console.log(test());

The result is

Angle --> console.log(obj.prop.getFullName()); 

and

David --> console.log(test());

Can you explain that? why the result is different? Thanks

Alex K.
  • 171,639
  • 30
  • 264
  • 288
jhonderiva
  • 25
  • 1
  • 6
  • 2
    `obj.prop.getFullName()` calls the function getFullName, `getFullname` gets the attribute. (`this` in the function = window, hence why it gets david also) – Carl Sep 30 '16 at 12:51
  • common javascript mistake, "this" is a funny, doing test = somefunc, is not the same as in other languages, (pointer to function). if you want to do that sort of thing in javascript you will need to use bind. eg. var test = obj.prop.getFullname.bind(obj.prop). – Keith Sep 30 '16 at 12:54
  • Urgh I was too slow. Here my answer: It's all about context. Inside the 'prop', the 'this' links to the 'prop' itself. But if you take just the method, the context of 'this' changes to the global context (window). – Mijago Sep 30 '16 at 12:54

0 Answers0