Method Calls on Objects 3 ?

When A Method Becomes A Function :
The fastest way is to assume that a function is assigned “this” based on the object on which it is defined.In fact, the value of “this” can change dramatically, not based on which object the method is embedded within, but based on the invocation pattern of the method (or function).

Example: take the “doStuff” method of “myObj” and assign it to a variable. Then call the function from that variable using the standard function invocation you saw yesterday.

  var fn = myObj.doStuff;
  fn();

what “this” will be in the “fn()” invocation?
The standard function invocation assigned “this” to either the “global” object or “undefined”. Does this invocation pattern look familiar? What, then, will “this” be assigned to? The answer is that it depends on the runtime and whether or not you’re in strict mode!

But … Why?

When you assigned the “doStuff” method to the “fn” variable, it ceased being a method – at least, in the “fn” variable. It became a function by virtue of not having an object on which it was invoked. The call to “fn()” was a simple, ordinary function call – an invocation pattern , which told you that the value of “this” was either the global object of the runtime, or undefined.

Therefore, it is the “.” (dot-notation) syntax that turns a function invocation in to a method call on an object, and not the fact that the function was defined on that object.

Method calls – functions that are invoked on an object – set the value of “this” to the object on which they are invoked. But defining a function on an object does not mean the function will be invoked on that object. It truly is the invocation pattern that determines the value of “this”, and not just the location of the function definition.

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Javascript
One comment on “Method Calls on Objects 3 ?
  1. David says:

    This was a very simple, but effective example. Thanks!