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;
优势:全部实例能够共享原型对象中的属性和方法
缺点:若是原型对象中的属性是引言类型,会致使全部实例的更改(官方:若是包含引用类型值的原型属性会被全部实例共享)(它的优势也便是他的缺点)
二、利用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
优势:在子类构造函数中能够向超类构造函数传递参数
缺点:不能实现函数复用(超类原型对象中定义的属性和方法不能共享)
三、组合式继承(将原型链和构造函数合在一块儿)
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
优势:能够共享原型对象的属性和方法,能够向超类传递参数
缺点:无论什么状况下,都会两次调用超类构造函数
四、利用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+;
五、利用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
}
}复制代码