Thursday, July 26, 2012

JavaScript HOW TO Verify Function exists in class

Hi, Readers.
Today i will explain how to verify in javascript whether the function/method and property/variable exists in class/object. Continue reading and i will teach how to...

The example(1) class we will work on is:
// class constructor
function Car(color){
   this.color = color;
   this.paint = function(color){
      this.color=color;
   };
}

The Example(2)
var Car = function(color){
   this.color = color;
};

Car.prototype.paint = function(color){
   this.color=color;
};

How to verify if property/variable or function/method exists in class/object in javascript?
for example(1), when function is defined as anonymous, we can use:
var c = new Car('red');
console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
// If you don't receive the 'Doesnt exists' in console, then the method/variable 
// is found, otherwise you will receive "Assertion failed: Doesnt exists"


On example(2) instance we should use a bit different construction.
Lookup in base object (not instance) On example(2) instance we should use a bit different construction.
Lookup in instantiated object
// lets see
c = new Car('red'); // instance
c.paint('blue');
alert(c.color); // alerts 'blue'

console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
console.assert(true === Car.prototype.hasOwnProperty('paint'));


Lookup for method/variable inside instantiated object in javascript
// lets see
c = new Car('red'); // instance
c.paint('blue');
alert(c.color); // alerts 'blue'

//previous try
console.assert(true === c.hasOwnProperty('paint'), 'Doesnt exists');
// new try
console.assert(true === c.__proto__.hasOwnProperty('paint'), 'Doesnt exists');

Why using __proto__ and what is exactly __proto__?
__proto__ is a "secret" reference to creator.

You can notice, that behavior of the method "paint" is as usual class method, it is painted our car to blue, but couldn't be found in class. Interesting?
This happens because it is defined with prototype and it is method of class' prototype that is also object.:)
The structure of the object Car
object Car
   property color
   object prototype/__proto__
      method paint

That is the prototype's behavior.
We will take a deeper look on prototypes and assertion in next articles.

Sincerely, Ruskevych Valentin

No comments: