Monday, April 14, 2014

JavaScript 02

Classes, prototypes,constructors

From wikipedia:
1) a class is an extensible template for creating objects.
2) provides initial values for state (member variables)
3) implementations of behavior (member functions, methods)

Does JavaScript have classes ?
Correct technical answer is: No.

Is JavaScript a class-based language ?
No, JavaScript is a prototype-based language.

Is it possible to use JavaScript like a class-based language ?

// Define a class like this
function Person(name, gender){

   // Add object properties like this = name;
   this.gender = gender;

// Add methods like this.  All Person objects will be able to invoke this
Person.prototype.speak = function(){
    alert("Howdy, my name is" +;

// Instantiate new objects with 'new' and assign to person variable
var person = new Person("Bob", "M");

// Invoke methods like this
person.speak(); // alerts "Howdy, my name is Bob"
When Object is called as part of a new expression, it is a constructor that may create an object.( ECMA-262 pg.124)

It  returns the object and sets the "this" keyword to the object Person (13.2.2 pg.112 ).

Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
So in case of Person 1 is true, if we think of it as a class. It is extensible. Point 2 is also true since you can provide initial values. And 3 is also true as you can add whatever you want to a class. A function an object. Etc.

 So does JS have classes. It can be made so that it appears as it does have them.

In prototype-based OO, new objects are created by copying other objects (instead of being instantiated from a class template), methods live directly in objects instead of in classes.
If an object doesn't have a method or property, it is looked up on its prototype(s), aka. the prototype chain.

Prototype chain (4.2.1 pg.15):
1) Every object created by a constructor has an implicit reference (called the object‘s prototype) to the value of its constructor‘s ―prototype property.

2) Let's check Object.propName

2.1) First the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers;

2.2) If that object does not contain the named property, the prototype for that object is examined next; and so on.

In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behaviour.

In ECMAScript, the state and methods are carried by objects, and structure, behaviour, and state are all inherited.

No comments:

Post a Comment