WinJS: Classes

 

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

function NewClass(value){
  console.log("NewClass Contructor");
  this.field_value = value;
}

// Instance member -  method
NewClass.prototype.method_log_hello = function(){
  console.log("NewClass method log hello: Hello world");
};

// Instance member - property
Object.defineProperty(NewClass.prototype, "property_field_value", {
   get: function(){ return this.field_value; },
   set: function(new_value){ this.field_value = new_value; }
});

// Static member - private member
NewClass._counter = 0;
NewClass.counter_value = function () {
 return _counter++;
};

 

 

 

 

Share
Leave a comment