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

来源:互联网 发布:针织短款开衫淘宝网 编辑:程序博客网 时间:2024/06/05 06:16

最近在研究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({
      constructorfunction(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中的同名方法。

     

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

     

    附上我的测试代码

  • 原创粉丝点击