Объектно-ориентированные возможности библиотеки WinJS

В JavaScript всё обрабатывается как объект.

Метод WinJS.Class.define позволяет создавать новые классы. У него три параметра:
  • Конструктор: The first parameter lets developers initialize a new object.
  • Члены экземпляра: The second parameter is the collection of instance members, which includes properties and methods.
  • Статические члены: The third parameter includes static properties and static methods.

// Create a class called Author
var Author = WinJS.Class.define(

function(name, title) {
    this.name = name;
    this.title = title;
}, {
    _Name: undefined,
    _title: undefined,
    name: {
        set: function(value) {
            this._Name = value;
        },
        get: function() {
            return this._Name;
        }
    },
    title: {
        set: function(value) {
            this._title = value;
        },
        get: function() {
            return this._title;
        }
    }
});
// instantiate the author class by invoking the constructor with 2 parameters
var author1 = new Author("Senthil", "WinJS recipes");
// display the name and the title in the console window.
console.log(author1.name);
console.log(author1.title);

Пространство имен WinJS.Class предоставляет следующие вспомогательные функции для определения классов:
  • define: This function defines a class using the specified constructor and instance members.
  • derive: This function creates a subclass for the specified class by using the prototype inheritance.
  • mix: This function defines a class using the specified constructor and combines the set of instance members specified by all the mixin objects.

Метод WinJS.Class.derive позволяет наследовать классы. Он принимает следующие параметры:
  • Базовый класс: The class that the current class needs to inherit from.
  • Конструктор: This parameter refers to the constructor function that can be used to initialize the class members.
  • Члены экземпляра: This parameter defines instance members, which includes properties and methods.
  • Статические члены: This parameter defines static properties and static methods.

// Create a class called Employee
var Employee = WinJS.Class.define(

function() {
    this.name = name;
    this.type = "Employee";
}, {
    _Name: undefined,
    _type: undefined,
    name: {
        set: function(value) {
            this._Name = value;
        },
        get: function() {
            return this._Name;
        }
    },
    type: {
        set: function(value) {
            this._type = value;
        },
        get: function() {
            return this._type;
        }
    }
});
var ContractEmployee = WinJS.Class.derive(Employee,

function(name) {
    this.name = name;
    this.type = "Contract Employee";
});
var ContractEmployee1 = new ContractEmployee("Senthil");
// display the name and the title in the console window.
console.log(ContractEmployee1.name);
console.log(ContractEmployee1.type);


Метод WinJS.Class.mix позволяет комбинировать методы и свойства из множества объектов. Это может пригодится для реализации множественного наследования. Метод принимает два параметра:
  • Constructor: The first parameter, which is used to initialize the class members.
  • Mixin: The second parameter is the array that takes the mixin methods.

// Create a class called Employee
var Employee = WinJS.Class.define(

function() {
    this.name = name;
    this.type = "Employee";
}, {
    _Name: undefined,
    _type: undefined,
    name: {
        set: function(value) {
            this._Name = value;
        },
        get: function() {
            return this._Name;
        }
    },
    type: {
        set: function(value) {
            this._type = value;
        },
        get: function() {
            return this._type;
        }
    }
});
var ContractEmployee = WinJS.Class.mix(

function(name) {
    this.name = name;
    this.type = "Contract Employee";
}, Employee);
var ContractEmployee1 = new ContractEmployee("Senthil");
// display the name and the title in the console window.
console.log(ContractEmployee1.name);
console.log(ContractEmployee1.type);

WinJS предоставляет следующие mixin-ы:
  • WinJS.Utilities.eventMixin: This mixin can be used to add the event management functionality to any type that you define. It includes functions like
  • WinJS.Utilities.eventMixin.addEventListener, WinJS.Utilities.eventMixin. removeEventListener, and WinJS.Utilities.eventMixin.dispatchEvent to raise and handle custom events that you define.
  • WinJS.Binding.dynamicObservableMixin: This function is used to add binding management functionality, in which developers can bind a user-defined object to a control that is capable of notifying listeners when the value of a property changes.

Переменная может иметь функциональную (function) или глобальную (global) видимость (scope). Эта возможность используется для реализации инкапсуляции в JavaScript.


(function(global) {
    // public method
    function GetPageViews() {
        return 1000;
    }
    //private method.
    function GetCPMRate() {
        return 1;
    }
    WinJS.Namespace.define("DeveloperPublish", {
        GetPageViews: GetPageViews
    });
})(this);
console.log(DeveloperPublish.GetPageViews());

Еще пример:

(function(global) {
    // public method
    function GetPageViews() {
        return 1000;
    }
    //private method.
    function GetCPMRate() {
        return 2;
    }

    function GetTotalRate() {
        return GetPageViews() * GetCPMRate();
    }
    WinJS.Namespace.define("DeveloperPublish", {
        GetPageViews: GetPageViews,
        GetTotalRate: GetTotalRate
    });
})(this);
console.log(DeveloperPublish.GetPageViews());
console.log(DeveloperPublish.GetTotalRate());