js继承的多种方式

6 篇文章 0 订阅
  1. 原型链继承
function Parent() {
	this.name = 'kevin';
}
function Child(){};
Parent.prototype.getName = function(){
	console.log(this.name);
}
Child.prototype = new Parent();
let child1 = new Child();
console.log(child1.getName());//kevin

缺点:
1. 引用类型的数据被所有实例共享
2. 在创建实例时无法向继承的对象传参

  1. 构造函数继承
function Parent(name) {
	this.name = name;
}
function Child(name) {
	Parent.call(this, name);
}
let child1 = new Child('kevin');
let child2 = new Child('lisa');
console.log(child1.name);//kevin
console.log(child2.name);//lisa

缺点:
1.方法都在构造函数中定义,每次创建实例都要初始化方法

  1. 组合式继承
function Parent(name) {
	this.name = name;
	this.arr = ['red','blue'];
}
Parent.prototype.getName = function(){
	console.log(this.name);
}
function Child(name, age) {
	Parent.call(this, name);
	this.age = age;
}
Child.prototype = new Parent;
Child.prototype.constructor = Child;
let child1 = new Child('kevin', 18);
child1.arr.push('pink');
console.log(child1.age);
console.log(child1.arr);
child1.getName(); 
let child2 = new Child('daisy', '20');
child2.arr.push('green');
console.log(child2.age);
console.log(child2.arr);
child2.getName(); 
  1. 原型式继承
就是Object.create()的仿写
function createObj(fn) {
	function F(){}
	F.prototype = fn;
	return new F();
}
var person = {
    name: 'kevin',
    friends: ['daisy', 'kelly']
}

var person1 = createObj(person);
var person2 = createObj(person);

person1.name = 'person1';
console.log(person2.name); // kevin

person1.friends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]

缺点:
1.所有实例共享引用类型的值

  1. 寄生式继承
function createObj(o) {
	var clone = Object.create(o);
	clone.sayName = function (){
		console.log('hi');
	}
	return clone	
}
缺点:
	跟构造函数一样,每次都会创建一次方法
  1. 寄生式组合继承
function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

function prototype(child, parent) {
    var prototype = object(parent.prototype);
    prototype.constructor = child;
    child.prototype = prototype;
}

// 当我们使用的时候:
prototype(Child, Parent);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值