Why is Undefined in this example in the second case?

  • 0
    var fullname = 'Mark Ivanov';
    var obj = {
       fullname: 'Joe Milner',
       prop: {
          fullname: 'David Smith',
          getFullname: function() {
             return this.fullname;
          }
       }
    };
    
    console.log(obj.prop.getFullname());
    
    var test = obj.prop.getFullname;
    
    console.log(test());
    JavaScript Anonymous, Feb 2, 2020

  • 2 Answers
  • 0
    This is the basic knowledge, without which you will step on a bunch of rakes, you detach the method from the object and it loses context.

    I recommend reading https://www.oreilly.com/library/view/ javascript-th ...

    Well, or at least https://learn.javascript.ru/bind
    Anonymous

  • 0
    Assigning let test = obj.prop.getFullname; loses the this context. You can bind the context using bind let test = obj.prop.getFullname.bind (obj); .
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!