|
mootools.js的最新版本是1.2.3,這里使用的是1.2.0。mootool被設(shè)計(jì)成非常緊湊的,模塊化的,面向?qū)ο蟮牡膉s庫(kù)。mootool中寫類用Class類。Class類由Native類new出來的:
復(fù)制代碼 代碼如下:
/*
*Script: Class.js
*/
var Class = new Native({
name: 'Class',
initialize: function(properties){
properties = properties || {};
var klass = function(empty){
for (var key in this) this[key] = $unlink(this[key]);
for (var mutator in Class.Mutators){
if (!this[mutator]) continue;
Class.Mutators[mutator](this, this[mutator]);
delete this[mutator];
}
this.constructor = klass;
if (empty === $empty) return this;
var self = (this.initialize) ? this.initialize.apply(this, arguments) : this;
if (this.options && this.options.initialize) this.options.initialize.call(this);
return self;
};
$extend(klass, this);
klass.constructor = Class;
klass.prototype = properties;
return klass;
}
});
Native方法是mootools中一個(gè)非常重要的方法,很多類都用它去組裝。如Window,Document,Event。當(dāng)然還有這里的Class,導(dǎo)入mootools后我們寫類時(shí)只需要用Class就行了。一個(gè)Person類:
復(fù)制代碼 代碼如下:
/**
* Person類
* @param {Object} name
*/
var Person = new Class({
initialize: function(name){
this.name = name;
},
setName : function(name) {
this.name = name;
},
getName : function() {
return this.name;
}
})
//new一個(gè)對(duì)象
var p = new Person("jack");
//測(cè)試set,get方法
console.log(p.getName());//jac
p.setName('andy');
console.log(p.getName());//andy
//測(cè)試instanceof及p.constructor是否正確指向了Person
console.log(p instanceof Person); //true
console.log(p.constructor == Person); //true
Native實(shí)際上只是一個(gè)普通函數(shù),它通過所傳參數(shù)組裝了一個(gè)類(function),最后返回該類(function)。既然Native是函數(shù),函數(shù)調(diào)用的方式是(),call,apply。但在mootools中卻用new Native(obj)方式。為何?原因只是使Native看起來更像一個(gè)類而已。
JavaScript技術(shù):javascript 寫類方式之十,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。