javascript实现OOP编程

1.首先通过一个函数来实现JS的单继承。使用原型方式来实现继承

 (function () {

     $.extend({
oop: {
extend: function (child, father) {
if (father == null) {
var father = function () { };
console.log(this);
father.prototype = this
}
child.prototype = new father(); child.base = father;
child.prototype.base = child.prototype;
}
} });
window.oop = $.opp;
})();

该方法向子类追加base实例属性及静态实例属性,以便找到父类。

2.创建一个基类。

 (function () {
oop.ui = function () {
/**
*渲染之前
*基类不开启渲染。
*/
this.renderBefor = function (self) {
return false;
}
/*
* 渲染函数
*/
this.render = function () {
if (this.renderBefor()==false) return;
if (this.element) {
this.element.wrap("<span class='oop_ui'></span>");
}
this.redered();
}
this.redered = function (self) { }
}
oop.extend(oop.ui);
})();

3.创建一个子类。

 (function () {
oop.ui.select = function ($input) { this.element = $input this.renderBefor = function () {
return true;
}
this.render = function () {
/**
*通过apply方法来调用基类的render方法。
*/
this.base.render.apply(this,arguments);
this.element.parent().addClass("oop-ui-select");
}
};
oop.extend(oop.ui.select, oop.ui); })();

子类oop.ui.select的render 方法中。

调用基类的方法是this.base.render.apply(this,arguments);

apply是将base.render()方法中的this覆盖为当前子类的this(也就是指向oop.ui.select)。

上一篇:扩展1 - Python 获取当前时间的用法


下一篇:ASP.NET MVC做的微信WEBAPP中调用微信JSSDK扫一扫