JavaScript, jQuery, and DOM model interaction

Slashdot it! Delicious Share on Facebook Tweet! Digg!

Inclusiveness

Perhaps more puzzling is the line var toGreet = who; . Caveat: In JavaScript, you can define inner functions that access variables from an outer function. Of course, the outer function can't access variables in the inner one, because that would result in a single scope of universal variables, which could cause a conflict.

Both calls of greeter1.sayHello() and greeter2.sayHello() also show that the who parameter value is stored in toGreet , even though the Greeter function was already executed. The reason is that the variable-bound functions in JavaScript have their run-time environment wrapped up in them. In concrete terms, this means all variables in the scope of sayHello that the function accesses will stay in memory, as long as the function itself is bound to a variable. The greeter1 and greeter2 functions are the ones responsible for this, taking sayHello() as an attribute. This technique is known as "closure."

The closure principle is really quite simple. The JavaScript interpreter goes through the code once before executing it and notes which parts of the program access which variable. In regard to how it decides how long a variable should stay in memory, there's a simple answer: Everything still needed remains in memory.

Parent and Child

I still haven't provided an explanation for the new keyword that creates the two object instances greeter1 and greeter2 (which produce the different values for toGreet ) out of the Greeter function definition.

Here, the function() and the object are identical, so the function changes the attribute assignment this.<attribute-name> itself. After executing the function, the new call sets the function-identical object to the variable greeter1 or greeter2 , just as the function will end with return this .

Object instances from a common definition are created in JavaScript via the call new <function-variable>(<parameter>) . Inside the function stored in <function-variable> are variables like private data fields or – if its content is a function – a private method. On the other hand, the this.<attribute-name> creates public attributes or methods.

Buy this article as PDF

Express-Checkout as PDF

Pages: 6

Price $0.99
(incl. VAT)

Buy Ubuntu User

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content