Base.js 库 实现 JS 的对象化编程

最近在研究JS的面向对象编程。

由于JS使用Function的概念来代替Class,往往使用这种方式来定义一个对象:

 

   function JSClass()
   {

    //成员变量
    this.m_Text = 'division element';
    this.m_Element = document.createElement('DIV');
    this.m_Element.innerHTML = this.m_Text;
   
    this.m_Element.attachEvent('onclick', this.ToString);
   }


   //成员方法 
   JSClass.prototype.Render = function()
   {
    document.body.appendChild(this.m_Element);
   }    

   JSClass.prototype.ToString = function()
   {
    alert(this.m_Text);
   };

 

   var jc = new JSClass();
   jc.Render();
   jc.ToString();

 

后来找到:

很多的JS项目中使用了这种方式来实现

引入一个老外牛人叫做(dean.edwards)开发的基类: base.js

然后,就可以更加面向对象的方式编写JS的class类了,还支持扩展等。

按照他的说法,写此基类的目的就是:

 

I want to easily create classes without the MyClass.prototype cruft I want method overriding with intuitive access to the overridden method (like Java’s super) I want to avoid calling a class’ constructor function during the prototyping phase I want to easily add static (class) properties and methods I want to achieve the above without resorting to global functions to build prototype chains I want to achieve the above without affecting Object.prototype

 

基本的使用方法就是:

 

var Animal = Base.extend({
  constructor: function(name) {
    this.name = name;
  },
  
  name: "",
  
  eat: function() {
    this.say("Yum!");
  },
  
  say: function(message) {
    alert(this.name + ": " + message);
  }
});

 

成员变量和方法的创建都比原来简单吧。

 

使用就是这样:

new Animal("cats").say("fish");

如果

 ani = new Animal();

那么ani.name 就是 undefined 了

 

 

继承:

 

var Cat = Animal.extend({
  eat: function(food) {
    if (food instanceof Mouse) this.base();
    else this.say("Yuk! I only eat mice.");
  }
});

 

可见,在子类中,使用this.base的方式来调用super中的同名方法。

 

更多的使用方法可以搜索这个作者的博客。

 

附上我的测试代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值