0

Suppose i have a object with properties and method.

When i assign this object to another object, and i execute following code. Its giving me undefined undefined output while printing object obj1 in console, can anyone please help me on this, and explain me this behaviour.

thank you.

var emp = {
  fname: "sachin",
  lname: "pawar",
  getname: function() {
    return this.fname + " " + this.lname;
  }
};
var obj = emp.getname;
var obj1 = obj();
var obj3 = emp.getname();
console.log(obj1);

2 Answers 2

1

The issue is that this in your getname method is undefined when called via the line:

var obj1 = obj();

In JavaScript this is dependent upon the context in which the function is called. So, when you call it as a 'dot method' against the emp object this refers to its containing object. Where you call it 'stand alone' it has no contect and this is undefined.

You can bind a standalone call to give it a context, as follows:

var obj=emp.getname.bind(emp);
var obj1=obj();

Then when it executes it will use emp to get its context for this.

Sign up to request clarification or add additional context in comments.

Comments

0

When you do obj = emp.getname, its reference is copied and when you call it, there is a difference in obj.function() and function().

When you do obj.function, function's this is set as obj, but when you copy reference and call it, since no object is associated to this call, it takes global scope(window). Hence it returns undefined.

Sample

window.fname = "Foo";
window.lname = "Bar";
var emp = {
  fname: "sachin",
  lname: "pawar",
  getname: function() {
    return this.fname + " " + this.lname;
  }
};
var obj = emp.getname;
var obj1 = obj();
var obj3 = emp.getname();
console.log(obj1);
console.log(obj3);

Alternate implementation

var emp = (function() {
  // private properties
  var fname = "sachin"
  var lname = "pawar"
  var getname = function() {
    return fname + " " + lname;
  }
  // Selected properties exposed
  return {
    getname: getname
  }
})()

var obj = emp.getname;
var obj1 = obj();
var obj3 = emp.getname();
console.log(obj1);
console.log(obj3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.