Home > Web Front-end > JS Tutorial > body text

JavaScript class inheritance and instantiation methods_javascript skills

WBOY
Release: 2016-05-16 15:49:13
Original
1161 people have browsed it

The examples in this article describe the methods of JavaScript class inheritance and instantiation. Share it with everyone for your reference. The details are as follows:

(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;
})();

Copy after login

Example:

//基类对象或函数
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
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template