JS定义类的方式及继承的方式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值