JavaScript中的5种继承方式

1. 构造函数的继承

function Person(name,age){
	this.name = name,
	this.age= age,
	this.sayHello = function(){
		Person.call(this,name);	
	}
}

function Male(name,age){
	Person.call(this,name,age); //改变this的指向
	this.sexy = "male";
}

var male = new Male("john",20);
console.log(male);

2. 原型继承

function Person(){}
Person.prototype.name = "john";
Person.prototype.age = 20;
Person.protoype.sayHello = function(){
	console.log(this.name);
}

function Male(){}
Male.prototype = new Person(); //形成原型链
Male.prototype.sexy = "male";

var male = new Male();
console.log(male.sexy);

3. 组合继承

function Person(name,age){
	this.name = name;
	this.age = age;
}

Person.prototype.sayHello = function(){
	console.log(this.name);
}

function Male(){
	Person.call(this,name,age);
}

for(let i in Person.prototype){
	Male.prototype[i] = Person.prototype[i];
}

Male.protype.sexy = "male";
var male = new Male("john",20);
male.sayHello();

4. 寄生式组合继承

function Person(name,age){
	this.name = name;
	this.age = age;
}
Person.prototype.sayHello = function(){
	console.log(this.name);
}

function Male(name,age){
	Person.call(this,name,age);
}
Male.prototype = Object.create(Person.prototype); //Object.create()创建一个空对象,这个空对象的__proto__指向Person.prototype
Male.prototype.constructor = Male; // 原型中的constructor指向本身构造函数,这里复原一下

var male = new Male("john",20);
male.sayHello();
//通过实例找构造函数
console.log(male.__proto__.constructor);

//原型的继承一般调用如下函数
function inherit(Sup,Sub){
	Sub.prototype = Object.create(Sup.prototype);
	Sub.prototype.constructor = Sub;
}

5. ES6继承

class Person{
	constructor(name,age){
		this.name = name;
		this.age = age;
	}
	sayHello(){
		console.log(this.name)
	}
	static foo(){ //静态方法 类方法
		console.log("foo");
	}
}

class Male extends Person{
	constructor(name,age){ //除了继承来的属性,自己需要添加属性
		super(name,age) //super指向父类的构造函数,同时创建this,改变this指向
		this.sexy = 'male'; //在使用this之前先调用super方法
	}
	sayHi(){
		console.log("hi");
		//在原型方法里需要使用父类的原型方法
		super.sayHello(); //super指向父类的原型对象
	}
	static bar(){
		super.foo();  //super指向父类
	}
}

var male = new Male("john",20);
male.sayHello();
male.sayHi();
Male.bar();
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值