模拟重载
function Person(){//person构造器
var args =arguments;
if(typeof args[0] === 'object' && args[0]){//判断是否是对象,并且不等于null
if(args[0].name){
this.name = args[0];
}
if(args[0].age){
this.age = args[0];
}
}else{
if(args[0]){
this.name = args[0];
}
if(args[1]){
this.age = args[1];
}
}
}
//重载
Person.prototype.toString = function(){
return 'name=' + this.name + ",age=" + this.age;
}
var bosn = new Person('Bosn',27);
bosn.toString(); //"name=Bosn,age=27"
var nunn = new Person(name:'Nunn',age:38);
nunn.toString();//"name=Nunn,age38"
调用子类的方法
function Person(name){this.name = name};//简化模型
function Student(name,className){
Person.call(this,name);//初始化基类
this.className = className;//初始化
}
var bosn = new Student('Bosn','Network064');
bosn;//Student{className:'Network064',name:Bosn};
//调用子类的方法
Person.prototype.init = function(){};
Student.prototype.init = function(){
Person.prototype.init.apply(this,arguments);
};
链式调用
function ClassManager(){
ClassManager.prototype.addClass = function(str){
console.log('class:'+str+' added');
return this;
}
}
var manager = new ClassManager();
manager.addClass('ClassA').addClass('ClassB').addClass('ClassC');//链式调用
//Class:ClassA added;
//Class:ClassB added;
//Class:ClassC.added;
抽象类 ES6
function DetectorBase(){ //抽象类
throw new Error('Abstract class can not be invoked directly! ');
}
DetectorBase.detect = function(){console.log('Detection starting……');};
DetectorBase.stop = function(){console.log('Detection stopped.');};
DetectorBase.init = function(){throw new Error('Error')};
function LinkDetector(){};
LinkDetector.prototype = Object.create(DetectorBase);
模块化
var moduleA;
moduleA = function(){
var prop = 1;
function func(){
return{
func :func;
prop:prop;
}
}
}();//方法默认有括号代表立即执行的
var moduleA;
moduleA = new function(){
var prop = 1;
function func(){};
this.func = func;
this.prop = prop;
};