js中继承的几种实现方式

一、继承
1、利用原型链实现继承
function SuperFn(){
	this.flag=true;
}
SuperFn.prototype.judgeFlag=function(){
	console.log("this.flag",this.flag)
}
function suberFn(name){
	this.flag=name
}
var s=new SuperFn()
suberFn.prototype=s;
优点:所有实例可以共享原型对象中的属性和方法
缺点:如果原型对象中的属性是引言类型,会导致所有实例的更改(官方:如果包含引用类型值的原型属性会被所有实例共享)(它的优点也即是他的缺点)
2、利用call方法实现继承(借用构造函数)
function superName(name){
  console.log("super")
  this.name=name	
}
function subName(age){
	console.log("suber")
	superName.call(this)
	this.age=age
}
superName.prototype.sayname=function(){
  console.log("name==",this.name)
}
subName.prototype=new superName()
subName.prototype.constructor=subName
优点:在子类构造函数中可以向超类构造函数传递参数
缺点:不能实现函数复用(超类原型对象中定义的属性和方法不能共享)
3、组合式继承(将原型链和构造函数合在一起)
function superType(name){
	console.log("super")
	this.name=name
}
function suberType(age){
	console.log("suber")
	superType.call(this,"lxx");  //第二次调用超类 superType
	this.age=age
}
superType.prototype.sayname=function(){
	console.log("name==",this.name)
}
suberType.prototype=new superType()  //第一次调用超类 superType
suberType.prototype.constructor=suberType
优点:可以共享原型对象的属性和方法,可以向超类传递参数
缺点:不管什么情况下,都会两次调用超类构造函数
4、利用Object.create实现继承
var person={
	name:'lxx',
	age:23,
	sex:1
}
var another=Object.create(person)
function animal(){
	this.say=true;
}
animal.prototype.sayname=function(){
	console.log("name==",this.say)
}
var dog=Object.create(animal.prototype) //利用Object.create(animal.prototype)来实现及继承
Object.create()方法MDN是上的标准解释是:Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__。 
Tips: Object.create(null)可以创建一个没有任何原型的对象
缺点:浏览器兼容问题,IE 9+,chorome,Safari 5+,Firefox 4+;
5、利用class(es6)语法实现继承
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
	return 3
  }
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}
class colorPoint extends Point{
	constructor(x,y,color){
		super(x,y);
		this.color=color
	}
}复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值