JavaScript继承

JavaScript继承

JavaScript所谓继承就是从其他对象获取的属性和方法,子类继承父类。

在JavaScript中查找属性和方法:

1.先在自身查找
2.沿原型链向上查找
3.没有找到则返回undefined

JavaScript中的继承方式:

一、通过在子类中调用父类的方式,改变父类的执行环境:

function Father(){
	this.name = 'father';
}

function Son(){
	this.name = 'son';
	// 调用父类
	this.father = Father;  
	this.father();
}

二、通过原型链继承:

function Father(){
	this.name = 'father';
	this.fn = function(){
		return this.name;
	};
}

function Son(){
	this.name = 'son';
}

Son.prototype = new Father(); // Son的原型是Father的实例 
Object.defineProperty(Son.prototype,'constructor',{
	value:'Son'    // 修复constructor
}); 

这种继承方式只继承了父类的共有属性和方法,即原型上的方法。

三、通过修改this指向,获得其他对象的方法:

function Father(){
	this.name = 'father';
}

function Son(){
	this.name = 'son';
	Father.call(this); // 修改this指向,并立即执行函数
	// Father.apply(this);
	// Father.bind(this)();
}

这种继承方式只继承了父类的私有属性和方法。
call()和apply()修改this指向后会立即执行函数,而bind()修改后返回新函数,不会立即执行。

四、混合继承:

基于上面二三两种继承方式,实现同时继承父类的共有和私有属性和方法。

function Father(){
	this.name = 'father';
}

function Son(){
	this.name = 'son';
	Father.call(this); // 继承私有
}

Son.prototype = new Father(); // 继承共有
Object.defineProperty(Son.prototype,'constructor',{
	value:'Son'    // 修复constructor
});

五、class继承:

JavaScript中的class其实是原型的语法糖。

class Father{
	constructor(){
		this.name = 'father';
	}
	fn(){
		console.log(this.name);
	}
}

class Son extends A{} // 使用extends关键字

六、通过Object.create():

Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。
Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

function Father(){
	this.name = 'father';
}

function Son(){
	this.name = 'son';
	Father.call(this); // 继承私有
}

Son.prototype = Object.create(Father.prototype); // 继承共有
// 相同的,使用Object.assign()
// Object.assign(Son.prototype,Father.prototype);
Object.defineProperty(Son.prototype,'constructor',{
	value:'Son'    // 修复constructor
});
  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值