本文实例讲述了JavaScript类继承及实例化的方法。分享给大家供大家参考。具体如下:
示例:
函数
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,//...
});
//从空对生成基类
var class_frome_base = Class.create({},//...
});
//实例化
var get_class_frome_obj = Class.new(class_frome_obj,[arg1,arg2,...]);
var get_class_frome_fun = Class.new(class_frome_fun,...]);
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程序设计有所帮助。