Alejandro G. Carlstein Ramos Mejia Blog



Deriving a Class (Inheritance)

We got this new class example:

var NewClass = WinJS.Class.define(function(value){
  console.log("NewClass constructor");
  this.field_value = value;
}, 
{ // Methods, properties and fields. Instance members.
  method_log_hello: function(){
    console.log("NewClass method log hello: Hello world");
  },
  property_field_value: {
    get: function(){ return this.field_value; },
    set: function(new_value){ this.field_value = new_value; }
  }
}, {
  // Static member - private member
   _counter: 0,
   counter_value: function () {
     return _counter++;
   }
});

And we wish to derive such class; therefore, we are going to do the following:

var NewSubClass = WinJS.Class.derive(NewClass, function(new_value, new_second_value){
  console.log("NewSubClass constructor");
  NewClass.call(this, new_value); // This is the equivalent to super in other languages.
  this.field_second_value = new_second_value;
}, { // Instance members
  new_method_log: function(){
    console.log("NewSubClass new_method()");
  }
},{ // Static and private members
  _second_counter = 0,
 second_counter_value: function () {
    return _counter++;
  }
}

Overriding Method

Share

 

Defining a Class

var NewClass = WinJS.Class.define(function(value){
  console.log("NewClass constructor");
  this.field_value = value;
}, 
{ // Methods, properties and fields. Instance members.
  method_log_hello: function(){
    console.log("NewClass method log hello: Hello world");
  },
  property_field_value: {
    get: function(){ return this.field_value; },
    set: function(new_value){ this.field_value = new_value; }
  }
}, {
  // Static member - private member
   _counter: 0,
   counter_value: function () {
     return _counter++;
   }
});

Alternative Way to Define a Class

var newClassConstructor = function(value){
  console.log("NewClass constructor");
  this.field_value = value;
};

var newClassMethods = { // Methods, properties and fields. Instance members.
  method_log_hello: function(){
    console.log("NewClass method log hello: Hello world");
  },
  property_field_value: {
    get: function(){ return this.field_value; },
    set: function(new_value){ this.field_value = new_value; }
  }
};

var newClassStaticAndPrivateMembers = {
  // Static member - private member
   _counter: 0,
   counter_value: function () {
     return _counter++;
   }
};

var NewClass = WinJS.Class.define(newClassConstructor, newClassMethods, newClassStaticAndPrivateMembers);

JavaScript Equivalent

Share