之前看了一些javascript的面向对象方法,主要是为了win8开发的学习。
在win8开发中,可以使用js定义类的方式进行定义,也可以用WinJS提供的方法,下面就对WinJS.Class提供的三个对类的基本操作函数进行简单的说明。
WinJS.Class.define
Syntax
var object = WinJS.Class.define(constructor, instanceMembers, staticMembers);
//基本类的定义
var Person = WinJS.Class.define(
function (name, sex) {
this.name = name;
this.sex = sex;
},
{
name: {
get: function () { return name; },
set: function (newname) { name = newname; }
},
sex: "",
sayHello: function () {
console.log("instanceMember:Person name is: "+ this.name +" and sex is: "+ this.sex);
}
},
{
sayHello: function () {
console.log("staticMember:Person");
}
});
var onePerson = new Person("kay", "male");
onePerson.sayHello(); //output: instanceMember:Person name is: kay and sex is: male
Person.sayHello(); //output: staticMember:Person
从代码中可以看出,在定义成员时,也可以像js一样,定义该成员的get/set访问函数。
WinJS.Class.derive
Syntax
var object = WinJS.Class.derive(baseClass, constructor, instanceMembers, staticMembers);
//继承
var Student = WinJS.Class.derive(Person,
function (name, sex, stuNo, dept) {
//Person.prototype.constructor(name, sex);
Person.call(this, name, sex);
this.stuNo = stuNo;
this.dept = dept;
},
{
doSomething: function () {
console.log("I'm "+this.name+" and my stuNo is "+this.stuNo);
}
},
{
sayHello: function () {
console.log("staticMember:Student");
}
});
var oneStudent = new Student("dan", "female", "20102100227", "math");
oneStudent.sayHello(); //output: instanceMember:Person name is: dan and sex is: female
oneStudent.doSomething(); //outout: I'm dan and my stuNo is 20102100227
Student.sayHello(); //output: staticMember:Student
从Student类的构造函数中可以看出,调用基类构造函数的方法有两种,都可以调用基类的构造函数进行初始化。
WinJS.Class.mix
Syntax
var object = WinJS.Class.mix(constructor);
//复合
var Chairman = WinJS.Class.define(null,
{
introductionMe: function () {
console.log("I'm the chairman");
}
});
WinJS.Class.mix(Chairman, Person);
var xiaohong = new Chairman();
xiaohong.introductionMe(); //output: I'm the chairman
xiaohong.sayHello(); //output: staticMember:Person
Chairman类和Person类进行复合之后,就可以使用Person类的sayHello()方法了。
从上面三个示例可以看出,WinJS对类的操作其实是更简单的,比起js,当然在web开发当然还是使用js,至于在win8中是不是真的WinJS使用起来会比较方便,这个还是需要自己通过实践之后才能对比出来。