On Sep 27, 3:06 pm, Karol Kowcik <kow_usun_...@gmail.comwrote:
Here's an example of 3 ways of using a method of an object with a
different object context. Is there a signficant difference between
method 1., where a reference to beta's method is copied and 2., where I
use call? To me no. 1 was a bit suprising, I expected that
alpha.introduce will point to beta.introduce, but will not change the
context of the function.
//simple object
var alpha={name:'alfa'}
//simple object, but can introduce itself
var beta={name:'beta',introduce:function() {alert(this.name)}}
//introduce beta
beta.introduce()
//1. alpha learns from beta how to introduce
alpha.introduce=beta.introduce
alpha.introduce()
//2.introduce alfa with a 'borrowed' method
beta.introduce.call(alpha)
//3.introduce alpha with a copied method
alpha.introduce=function() {return beta.introduce}()
alpha.introduce()
If a function is called as a property of an object, "this" always
refers to the object of which it is a property. Always, always,
always. A function can never be bound to one object with a "this"
reference of a different object. It doesn't work that way - that's
what Function.prototype.call and Function.prototype.apply are for.
You can consider those methods temporary "binders" which call a
function *as though* it were a property of the context object, while
leaving the context object itself intact. The difference being,
method 1 assigns a new property on your context object, while method 2
calls the function with the "this" context of the context object while
NOT assigning a new property to that object.
Method 3 then should be transparent - you're calling a function which
has a reference to a different object.
None of this has anything to do with "scope", a word that gets
transferred over from the Java/C++ world with none of the same
connotations. "Scope" in ECMAScript v3 refers to the resolving names,
and it exists at the function level, so a function has access to all
names that are in scope at its level or above, but no access to names
declared within functions inside of its scope. When resolving a name
used within a scope, the interpreter first checks for names defined
within the most local scope and proceeds outward to the global scope
on what you hear referred to as the "scope" chain. The "this" keyword
has no influence on scope, only on properties of objects, whose scope
is tied to the parent object's scope.
Hope that's clear as mud now!
-David