1

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Michael
  • 13,950
  • 57
  • 145
  • 288

5 Answers5

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() {
    ...
  }
};
pimvdb
  • 151,816
  • 78
  • 307
  • 352
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);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

you reference on a function, not on all object.

f = emp;   
f.paycheck();
Dezigo
  • 3,220
  • 3
  • 31
  • 39
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".

Community
  • 1
  • 1
nshew13
  • 3,052
  • 5
  • 25
  • 39
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();
Kos
  • 70,399
  • 25
  • 169
  • 233