win8: WinJS的面向对象 WinJS.Class

官方文档:http://msdn.microsoft.com/en-us/library/windows/apps/br229776.aspx

WinJS.Class.define 类定义

var object = WinJS.Class.define(constructor, instanceMembers, staticMembers);

三个参数是:构造函数,实例成员集合,静态成员集合。e.g.

win8: WinJS的面向对象 WinJS.Class
var Robot = WinJS.Class.define( function(name) {
    this.name = name;
}, 
{ modelName: "" }, 
{ harmsHumans: false });

var myRobot = new Robot("Mickey");

myRobot.modelName = "4500";
Robot.harmsHumans = false;
win8: WinJS的面向对象 WinJS.Class

对应的js代码是:

win8: WinJS的面向对象 WinJS.Class
function Robot(name) {
    this.name = name;
}

Robot.prototype.modelName = '4500';
Robot.harmsHumans = false;
win8: WinJS的面向对象 WinJS.Class

在JS中用 Object.defineProperty 定义modelName GET/SET时我们需要这么做:

Object.defineProperty(Robot.prototype, "modelName", {
    get: function () { this.computeModelName(); }
});

但在WinJS中:

win8: WinJS的面向对象 WinJS.Class
var Robot = WinJS.Class.define(
    function (name) { this.name = name; },
    {
        modelName: { get: function () { return this.computeModelName(); } }
    }
);
win8: WinJS的面向对象 WinJS.Class

 

WinJS.Class.derive 继承

 

var object = WinJS.Class.derive(baseClass, constructor, instanceMembers, staticMembers);

 

它通过调用Object.create 使用baseClass 的prototype 构造派生对象。

win8: WinJS的面向对象 WinJS.Class
var SpaceRobot = WinJS.Class.derive(Robot, function (name) {
    this.name = name;
},
{ airSupply: "" },
{ saveSelf: true });

var mySpaceRobot = new SpaceRobot("Myra");
mySpaceRobot.airSupply = "oxygen";
var save = SpaceRobot.saveSelf;
win8: WinJS的面向对象 WinJS.Class

WinJS.Class.mix 混合类

var object = WinJS.Class.mix(constructor);
win8: WinJS的面向对象 WinJS.Class
WinJS.Namespace.define("Robotics", {
    Robot: WinJS.Class.define( function(name) {
        this.name = name;
        }, 
        { name: name }, 
        { harmsHumans: false, obeysOrders: true })
    }); 

var Movable = {
    goForward: function () {
        document.getElementById("div").innerText = "go forward";
    },
    goBack: function () {
        document.getElementById("div").innerText = "go back";
    },
    turnRight: function () {
        document.getElementById("div").innerText = "turn right";
    },
    turnLeft: function () {
        document.getElementById("div").innerText = "turn left";
    };

WinJS.Class.mix(Robotics.Robot, Movable);

var myRobot = new Robotics.Robot("Mickey");

myRobot.goBack();
win8: WinJS的面向对象 WinJS.Class

当对象与WinJS.Utilities.eventMixin 等混合时,可以获取事件监听的功能等......

More info about mix , Check:http://msdn.microsoft.com/en-us/library/windows/apps/hh967789.aspx

 

 本文转自老Zhan博客园博客,原文链接:http://www.cnblogs.com/mybkn/archive/2012/10/04/2711519.html,如需转载请自行联系原作者

上一篇:旋转立方体(opengl)


下一篇:c# web中实现文件上传下载的三种解决方案(推荐)