sergionni
sergionni

Reputation: 13530

`apply` doesn't work for function as object's property

According to JavaScript Patterns book (p. 79), this should work:

 var ob = {
    fn: function foo(m) {alert(m);}
 };
 fn.apply(ob,['m']);

It doesn't work.

fn is not defined error thrown.

These 2 work OK:

ob.fn.apply(ob,['m']);

and

ob.fn.apply(null,['m']);

Why doesn't just fn.apply(ob,['m']) work? Can't get it.

Upvotes: 1

Views: 371

Answers (2)

canon
canon

Reputation: 41715

fn isn't defined in the global scope. It's a member of ob. If that came from a book it's a typo.

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179284

fn doesn't work because it's not a variable in scope. If window.fn was defined, or var fn was defined elsewhere, then you'd be able to access it as fn.apply. Because neither of those are defined, you need to use the full path to the function on the object:

ob.fn.apply(...);

If you want fn to be defined, you could simply set it:

var ob,
    fn;

ob = {
  fn:function(){...}
};
fn = ob.fn;

fn.apply(ob, ...);

Upvotes: 4

Related Questions