Method Calls on Objects 2 ?

Go back to the simple rule which was :

"Method calls assign "this" to the object from which they are called"

.Let’s dissect this and assign each part of the rule to the above code.

1) Method call: A method is a function attach to an object. Therefore the method being called is “doStuff”.
2) Object from which they are called: This is the object to which the method is attached, via the “.” notation. In this case, the “doStuff” method is attached to the “myObj” object via the “.” notation.
3) Assign “this” to the object: the actual assignment of “this” is the object on which the function was called. we can deduce that “this” in the “myObj.doStuff()” method call will be the object literal that is assigned to the “myObj” variable.

But… Why?

It turns out the “.” (dot-notation) method call is the important factor. When JavaScript sees an object-dot-method invocation, it uses the “.” to determine what “this” gets assigned to. Quite simply, the object on the left hand side becomes the value of “this”. Therefore, in the call to “myObj.doStuff()” the value of “this” is assigned to “myObj” – or, more accurately, the object to which the “myObj” variable points.

This is generally called method invocation, where a method is a function attached to an object. The value of “this” in method invocation is generally the object on which the method was called.

There are some exceptions to this rule, of course. The most notable of the exceptions is the use of the “new” keyword. There are also ways of overriding what “this” evaluates to, and even losing “this” along the way.

More Info:This


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

Posted in Javascript