JS定义类方式:
①:工厂方式
function createStuFactory(){
Var stu = new Object();
stu.name=”lidiansheng”
stu.age=23;
stu.show = function(){alert(stu.name+stu.age);}
return stu;
}
②:构造函数方式
function studentconstract(name,age){
this.name = name;
this.age = age;
this.show = function(){alert(stu.name+stu.age);}
}
Var stu = studentconstract(“lidiansheng”,23);
Stu.show();
此方法会造成每个对象都有独立的方法版本
③:原型方式
function() student(){}
student.prototype.name=”lidiansheng”;
student.prototype.age=23;
student.prototype.show=function(){alert(this.name);}
此方法可以实现类中属性和方法的共享,当更改任何一个对象的属性,都会影响其他对象的属性
④混合方法(构造函数方式定义对象的所有非函数属性,用原型方式定义对象的函数属性。)
function student(name,age){this.name=name;this.age=age;}
student.prototype.show = function(){alert(this.name);}
⑤动态原型方式(与混合方式十分相似)
function student(name,age){
this.name=name;
this.age=age;
if(typeof(student.init)==”undefined”){
student.prototype.show=function(){
alert(this.name);
}
student.init=true;
}
}
JS继承方式的实现
① 伪装继承方式
function Person(name,age){
this.name=name;
this.age=age;
this.show=function(){alert(this.name);}
}
function Coder(name,age){
this.constructer=Person;//设定Person方法为程序员类的一个方法
this.constructer(name,age);//调用Person方法为程序员类的属性赋值
delete this.constructer;
}
多重继承则可以再Coder中再加几个this.constructer2 = Person2 。。。。。
② Function对象
利用call()和apply()方法
function Person(name,age){
this.name=name;
this.age=age;
this.show=function(){alert(this.name);}
}
function Coder(name,age){
Person.call(this,name,age);
或Person.apply(this,new Array(name,age));
this.code=function(){alert(“I am coding”);}
}
③:原型链
function Person(name,age){
this.name=name;
this.age=age;
this.show=function(){alert(this.name);}
}
function Coder(){}
Coder.prototype=new Person(“lidiansheng”,23);//关键代码
Coder.prototype.code=function(){alert(“I am coding”);}
JS定义类的方式及继承的方式
最新推荐文章于 2023-06-09 20:47:26 发布