0

I'm using the following JavaScript code:

var emp= new Object();
emp["name"]="pooja";
emp["salary"]=725;

emp["paycheck"]=function()
 {
  var monthly=this["salary"]/12;
  alert(this["name"]+":"+monthly);
 };

emp["paycheck"]();       --work properly 
document.write("<br/>");
var f=emp["paycheck"];    --dosen't work
f();

f() have to get reference on emp["paycheck"] function and display a suitable answer. but insted i get NaN.

As i understood f() dosen't see the property of emp object("name" and "salary"). My question is why f() dosen't see the properties?

5 Answers 5

4

You refer to salary as this["salary"]. If you store the function and call it later, the this value is lost. It is only bound to the object if you directly call it, as in emp.paycheck(). You could pass the this value explicitly, though:

f.call(emp);

But you might rather want to refer to salary in the function as emp["salary"], since that will always work.

Note that instead of foo["bar"] you can use foo.bar, and that the new Object() part can just be:

var emp = {
  name: "pooja",

  salary: 725,

  paycheck: function() {
    ...
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

This method is the far more commonly accepted way to build an object.
2

The reason why is you are calling the function without a this parameter. You need to use apply to pass it an explicit this on which it can call the name and salary properties.

f.apply(emp);

Comments

1

you reference on a function, not on all object.

f = emp;   
f.paycheck();

Comments

1

You didn't copy those properties to f. There are, unfortunately, no native ways to do this in JavaScript. See How do I correctly clone a JavaScript object? or What is the most efficient way to deep clone an object in JavaScript?, look at jQuery's extend(), or google "javascript deep copy object" or "javascript clone object".

Comments

1

Others have explained what's going on and how you don't pass this.

However, if you want to do something like this (a custom from Python perhaps?), you can make a helper function:

function makeDelegate(obj, fun) {
    return function() {
        fun.apply(obj, arguments);
    };
}

Then use it like this:

var f = makeDelegate(emp, emp["paycheck"]);
f();

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.