之前一直使用别人包装好的组件,比如玉伯开发的Alare组件,用的很舒服啊~~
但是不是什么项目都要使用那么复杂的组件吧,如果用JQ自己写一个呢,JQ好像还没有类的包装,可能以后会有吧。
研究了半天发现了一个好东西,就是John Resig写的 Simple JavaScript Inheritance。
真是完美的解决了我的需求,而且代码也很少,下面就放上示例
JS代码如下:
/**
* 使用Simple Inheritance创建类
*
* @param
* @arrange (512.笔记) jb51.cc
**/
(function() {
/*
* Simple Inheritance
*/
var initializing = false;
var fnTest = /xyz/.test(function() {
xyz;
}) ? /\b_super\b/ : /.*/;
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
});
})
// 来自:编程之家 jb51.cc(jb51.cc)
原文链接:https://www.f2er.com/js/527637.html