DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript類繼承及實例化的方法
JavaScript類繼承及實例化的方法
編輯:關於JavaScript     

本文實例講述了JavaScript類繼承及實例化的方法。分享給大家供大家參考。具體如下:

(function(){
  var Class = {
    //擴展類
    create: function(aBaseClass, aClassDefine){
      var $class = function(){
        for(var member in aClassDefine){
          this[member] = aClassDefine[member];
        }
        if('undefined'===typeof aClassDefine.initialize){
          this.initialize = function(){};
        }
      };
      if('function' ===typeof aBaseClass){        
        $class.prototype = new aBaseClass();        
      }else if('object' ===typeof aBaseClass){
        $class.prototype = aBaseClass;
      }    
      return $class;
    },
    //實例化類
    new: function(jclass,args){
      var jclass = new jclass();
      if(jclass.initialize){
        jclass.initialize.apply(jclass, args);
      }
      return jclass;
    }
  };
  //export
  window.Class = Class;
})();

示例:

//基類對象或函數
var obj = {
  name: 'BaseName',
  init: function(){
    //...  
  },
  //...
};
var fun = function(){
  this.name = '';
  var init = function(){
    //..  .
  };
  var getName = function(){
    return this.name;
  },
  var setName = function(name){
    this.name = name;
    return this;//鏈式操作支持
  },
  //...
};
//從Object繼承
var class_frome_obj = Class.create(obj,{
  initialize: function(){
    //構造函數
  },
  getName: function(){
    return this.name;
  },
  setName: function(name){
    this.name = name;
    return this;//鏈式操作支持
  },
  //...
});
//從Function繼承
var class_frome_fun = Class.create(fun,{
  initialize: function(){
    //構造函數
  },
  //...
});
//從空對生成基類
var class_frome_base = Class.create({},{
  initialize: function(){
    //構造函數
  },
  //...
});
//實例化
var get_class_frome_obj = Class.new(class_frome_obj,[arg1,arg2,...]);
var get_class_frome_fun = Class.new(class_frome_fun,[arg1,arg2,...]);
var name1 = get_class_frome_obj.getName();
//console.log(name1);//BaseName
var name2 = get_class_frome_obj.setName('NewName').getName();
//console.log(name2);//NewName

希望本文所述對大家的javascript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved