JavaScript类的继承特性

在js中并没有类似于java中的extends关键字去继承其他的一个类。我们可以通过以下的方式去实现js中的继承特性。

 

方法一:对象冒充

function Parent(username) {
	this.username = username;
	this.hello=function() {
		alert(this.username);
	}
}

function Child(username,password) {
	this.method = Parent;
	this.method(username); //这句话是关键
	delete this.method;

	this.password = password;
	this.world=function(){
		alert(this.password);
	}
}
	
var parent = new Parent("lgk");
parent.hello();  //lgk
	
var child = new Child("ahau","aaa");
child.hello();  //ahau
child.world();  //aaa

 

 

方法二:function的call()方法

function Parent(username) {
	this.username = username;
	this.hello=function() {
	alert(this.username);
	}
}

function Child(username,password) {
	Parent.call(this, username);

	this.password = password;
	this.world=function(){
		alert(this.password);
	}
}
	
var parent = new Parent("lgk");
parent.hello();  //lgk
	
var child = new Child("ahau","aaa");
child.hello();  //ahau
child.world();  //aaa

 call是每个function中都有的方法,call中的第一个参数表示将谁传递给调用了call方法的函数(在这里也就是将Child传递给Parent),从第二个开始后面的参数都是以此对应传递给Parent中的参数

 

方法三:function的apply()方法

function Parent(username) {
	this.username = username;
	this.hello=function() {
		alert(this.username);
	}
}

function Child(username,password) {
	Parent.apply(this, new Array(username));

	this.password = password;
		this.world=function(){
			alert(this.password);
		}
	}
  var parent = new Parent("lgk");
parent.hello();  //lgk
	
var child = new Child("ahau","aaa");
child.hello();  //ahau
child.world();  //aaa

 apply中的第一个参数和call中的一样,apply中只有2个参数,第二个参数是一个数组,数组中的元素依次对应Parent中的参数。

 

方法四:原型链方式。

function Parent() {
		
}
Parent.prototype.username = "lgk";
Parent.prototype.sayHello=function(){
	alert(this.username);
}


function Child() {
		
}
Child.prototype = new Parent();//这句话是最关键的,它将Parent上的所有属性和方法都附加在了Child.prototype上
Child.prototype.password = "ahau";
Child.prototype.sayWorld=function(){
	alert(this.password);
}
	
var child = new Child("ahau","aaa");
child.sayHello();   //lgk
child.sayWorld();  //ahau

 

 方法五:混合方式(属性用构造方法的方式,方法用原型的方式)

function Parent(hello){
	this.hello = hello;
}

Parent.prototype.sayHello=function() {
	alert(this.hello);
}


function Child(hello,world){
	Parent.call(this, hello);
	this.world = world;
}

Child.prototype = new Parent();
Child.prototype.sayWorld=function() {
	alert(this.world);
}

	
var child = new Child("ahau","aaa");
child.sayHello(); //ahau
child.sayWorld(); //aaa

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值