这篇文章主要为大家详细介绍了JavaScript 使用Simple Inheritance创建自己的类示例,具有一定的参考价值,可以用来参考一下。
感兴趣的小伙伴,下面一起跟随四海网的小编罗X来看看吧。最近一直再研究类的写法。因为经常做一些可复用,可扩展的方法。
/**
* 使用Simple Inheritance创建类
*
* @param
* @arrange (512.笔记) www.q1010.com
**/
(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
});
})
// 来自:四海网(www.q1010.com)
本文来自:http://www.q1010.com/174/1746-0.html
注:关于JavaScript 使用Simple Inheritance创建自己的类示例的内容就先介绍到这里,更多相关文章的可以留意四海网的其他信息。
关键词:Simple,Inheritance
四海网收集整理一些常用的php代码,JS代码,数据库mysql等技术文章。