home / experts / javascript / column80 |
|
Defining MethodsFunctions in JavaScript can modify global variables from the outer context. Let's see an example. We initialize a global variable to 5, and each function definition below adds 10 to it within its definition. We then print the final value. Notice that each click below will increment the variable
Pass The second way to define a function is the anonymous way. You define a function inline, without giving it a name:
Pass The third way to define a function is by constructing it with the
Pass When you define an object's method, you may want to define and use a private data member. A private data member is a variable that is local to an object. It is included in the context of the object, and is a kind of global variable. Unlike the previous behavior where all function types succeeded in modifying the global variable, changing a private data member is more risky. Let's take an example. We initialize a global variable to 5, and each function definition below adds 10 within its definition. The traditional and anonymous definitions do modify the global variable, but the constructor definition does not. In fact, you get an error message when trying to access a global variable from inside the constructor definition. Notice that each click below will increment the global variable by 10. Here are the class and object definitions:
Let's try calling all methods: traditional, anonymous, and constructor. You get an error when trying to access private data member with the constructor function. We can conclude that you need to use the traditional and anonymous function definitions in order to access private data members. The constructor definition does not support any access to private data members. Next: How to classify contexts |
Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: March 26, 2001
Revised: March 26, 2001
URL: http://www.webreference.com/js/column80/4.html