Pages

Wednesday, October 6, 2010

OOP Javascript Inheritance


// Inheritance
function RunSampleE() {

var Dog = function (id, name, age, color) {
Dog.prototype.Color = color;
Dog.prototype.Age = age;
Dog.prototype.ID = id;
Dog.prototype.Name = name;
Dog.prototype.toString = function () {
return this.ID + '; ' + this.Name + '; ' + this.Age + '; ' + this.Color;
}
Dog.prototype.Bark = function () { alert('Hoow, Hoow'); }
}

// var buddy = new Dog(1, 'Buddy', 3, 'White');
var buddy = new Dog.prototype.constructor(1, 'Buddy', 3, 'White');
alert(buddy);
buddy.Bark();
Dog.prototype.New = function () { alert('Say new'); }
buddy.New();
}

OOP Javascript (Hints)

Hints
  • Use Visual studio 2010, for writing all the code, it support intellisense
  • Use /// , inside the Javascript file to reference other just to support intellisense
  • when you define function as class, like
    var Dog = function (id, name, age, color) {
    this.Color = color;
    this.Age = age;
    this.ID = id;} //you cannot use Dog.Color [Wrong]

    you have to initiate the object first like

    var buddy = new Dog(1, 'Buddy', 3, 'White');
    then you will call buddy.Color.