Thursday, 3 January 2013

Previous Interview Question Next Interview Question

What is a method in javascript

Although the code shown above accomplishes what it is supposed to do, it has a serious limitation: it works only on a stopwatch object named "watch". If we were using multiple stopwatch objects to represent the times of several participants in a race (such as "watch1" and "watch2"), we would have to duplicate the code once for each object, changing the object name "watch" to the name of the new object in each replication.
This is more work than most programmers are willing to do. The object-oriented answer to this problem is a special kind of function call a method. Methods are functions that belong to objects, and for that reason they are sometimes called "member functions." Member functions are designed to operate directly on the properties of the object to which they belong.
Let's rewrite the previous sample code as a member function. Creating member functions requires two steps. First, we define a generalized function that does not apply to any object in particular:
// Step 1:
function update_by_5 ()
 this . minutes += 5;
 if (this . minutes > 59)
  this . minutes -= 60;
  this . hours += 1;
The JavaScript interpreter recognizes the word "this" as a synonym for "the object to which I belong." Since at this point the update_by_5 function doesn't actually belong to an object, the concept of "this" doesn't have much meaning. Step 2 provides the cure for this problem:
// Step 2:
watch . update = update_by_5;
This assignment statement tells the interpreter to let update be a member function of the watch object. It says that update's behavior should be the same as specified for update_by_5.
Now that watch has an update () method, we can invoke it with the following statement:
watch . update ();
This statement tells the JavaScript interpreter to run the update_by_5 function with the word "this" replaced by "watch". As a result, watch's member variables, hours and minutes, will be replaced with values that represent a time that is 5 minutes later.
If there are other stopwatch objects, the update_by_5 function can be attached to them as well. There is no practical limit on the number of objects to which a single function can be attached.

Previous Interview Question Next Interview Question


Post a Comment