最近一直再研究类的写法。因为经常做一些可复用,可扩展的方法。之前一直使用别人包装好的组件,比如玉伯开发的Alare组件,用的很舒服啊~~
但是不是什么项目都要使用那么复杂的组件吧,如果用JQ自己写一个呢,JQ好像还没有类的包装,可能以后会有吧。研究了半天发现了一个好东西,就是John Resig写的 Simple JavaScript Inheritance。
真是完美的解决了我的需求,而且代码也很少,下面就放上我使用的代码示例
代码如下 |
复制代码 |
(function() {
/*
* Simple Inheritance
*/
var initializing = false;
var fnTest = /xyz/.test(function() {
xyz;
}) ? /b_superb/ : /.*/;
this.Class = function() {};
Class.extend = function(prop) {
var _super = this.prototype;
initializing = true;
var prototype = new this();
initializing = false;
for (var name in prop) {
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn) {
return function() {
var tmp = this._super;
this._super = _super[name];
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
function Class() {
if (!initializing && this.init)
this.init.apply(this, arguments);
}
Class.prototype = prototype;
Class.constructor = Class;
Class.extend = arguments.callee;
return Class;
};
})();
$(function() {
//定义一个Box的类
var Box = Class.extend({
init: function(opts) {
opts = $.extend({
"element": 'box'
}, opts || {});
this.opts = opts;
this.element = $(opts.element);
this.render();
},
render: function() {
var elEl = this.element;
elEl.html(this.opts.name + ',' + this.opts.age);
this.show();
},
show: function() {
var elEl = this.element;
elEl.show();
}
});
//实例1 - 直接用new来实例化Box
var mybox = new Box({
element: '.mybox',
name: '张三',
age: 15
});
//实例2 - 先扩展,再用new来实例化Box
var mybox2 = Box.extend({
init: function(opts) {
this.opts = opts;
this.element = $(opts.element);
this.render();
this.event();
},
hide: function() {
var elEl = this.element;
elEl.hide();
},
event: function() {
var elEl = this.element;
var that = this;
elEl.on('click', function() {
that.hide();
})
}
});
new mybox2({
element: '.mybox2',
name: '李四',
age: 55
});
}) |
|