-
js继承
-
原型链继承:将子类的原型指向父类
缺陷: 1. 因为子类通过prototype对父类实例化继承了父类,所以父类上的引用类型的属性会被所有实例共享,其中一个实例改变它的值,其他实例中的值也会发生改变。
2. 在实例化子类时,是无法向父类传递参数的,实际上应该是说无法在不影响所有对象实例的情况下,给父类构造函数传递参数。
functions Son() {} functionFather() {} Son.prototype = new Father(); Son.prototype.constructor = Son;
-
借用构造函数继承
这种方法的缺陷在于:子类只继承了父类的属性,原型上的方法没有继承,无法获取。
function Son(name,age,sex) { this.name = name; this.age = age; this.sex = sex; Father.call(this,name,age,height); } function Father(name,age,height){}
-
组合继承:组合继承 = 原型链继承 + 借用构造函数继承
缺陷: 在构造函数继承(call方法那里)执行了一遍父类构造函数,在原型继承(Son.prototype = new Father)又执行了一遍构造函数,因此这种继承方式执行了两边父类构造函数。
function Son(name,age,sex) { this.name = name; this.age = age; this.sex = sex; Father.call(this,name,age,height); } function Father(name,age,height){} Son.prototype = new Father(); Son.prototype.constructor = Son;
-
原型式继承
特点:在没有创建构造函数的情况下,让一个对象和另一个对象保持相似,但是缺点和原型链继承类似,一个对象对引用类型属性进行修改了,其他对象中的这个属性也会被改变。
function object(o){ function F(){}; F.prototype = o; return new F(); } ES5中的Object.create()和object()方法功能类似。 let person = { name:'tu', friends:['Shelby','Court','Van'] }; var otherPerson = Object.create(person); otherPerson.name = 'min'; otherPerson.friends.push('Rob'); var otherPerson2 = Object.create(person); otherPerson2.name = 'qiang'; otherPerson2.friends.push('Barbie'); console.log(person.friends) //['Shelby','Court','Van','Rob','Barbie']
-
寄生式继承
特点:这种继承模式有点类似于工厂模式创建对象,用这种继承方式类为对象添加函数,会由于不能做到函数的复用而降低效率。
function createObject(o){ function F(){}; F.prototype = o; return new F(); } function createBook(obj) { var o = new createObject(obj); o.getName = function() { console.log('getName'); } return o; } var book = { name:'js book', alikeBook:['css book','html book'] } var anotherBook = createBook(book); anotherBook.getName() //'getName'
-
寄生组合式继承
function createObject(o){ function F(){}; F.prototype = o; return new F(); } function inheritPrototype(subType,superType) { var p = createObject(superType.prototype); p.constructor = subType; subType.prototype = p } function SuperType(name) { this.name = name; this.colors = ['red','blue','green']; } SuperType.prototype.sayName = function() { console.log(this.name); }; function SubType(name,age) { SuperType.call(this,name); this.age = age; } inheritPrototype(SubType, SuperType); SubType.prototype.sayAge = function() { console.log(this.age); }
-
es6中的class继承
class Person{ constructor(name,color){ this.name=name; this.color=["red","blue","green"]; } sayName(){ alert(this.name); } } class Student extends Person(){ constructor(name,color,score){ super(name,color);//调用父类构造函数 this.score=score; } showScore(){ alert(this.score); } } let stu1=new Student("xuxu",["white","black","pink"],90); stu1.sayName();//"xuxu" stu1.showScore();//90
ES5继承和ES6继承的区别:
ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上(Parent.apply(this))。
ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以 必须先调用super方法),然后再用子类的构造函数修改this。
-
js继承
最新推荐文章于 2024-06-14 14:37:58 发布