javascript 写类方式之九


9、YUI的写类方式
这里引入的是YUI 2.7.0版,只需引入yahoo.js。YUI引入了命名空间,类似于java的包。以下yahoo的工具函数包
写类方式:
复制代码 代码如下:

//定义包名
YAHOO.namespace("test");

//定义类
YAHOO.test.Person = function(name) {
this.name = name;
}
YAHOO.test.Person.prototype.setName = function(name){ this.name = name;}
YAHOO.test.Person.prototype.getName = function(){ return this.name;}


//创建一个对象
var p = new YAHOO.test.Person("jack");

console.log(p.getName());//jack
p.setName('tom');
console.log(p.getName());//tom

//测试instanceof及p.constructor是否正确指向了YAHOO.test.Person
console.log(p instanceof YAHOO.test.Person);
console.log(p.constructor == YAHOO.test.Person);

可以看出除了多了包名,与第三种写类方式 并无区别。
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3