*新闻详情页*/>
原理:让SuperType的实例成为子类的原型对象,子类的实例拥有了父类的属性和方法。但也有弊端,如果父类的属性是引用类型,这将导致共享的属性被改变的时候,全部的属性将被改变,我们一下代码。
function SuperType() { this.property = [1,2,3]; SuperType.prototype.getSuperValue = function() { return this.property; function SubType() { ths.subproperty = false; SubType.prototype = new SuperType(); // 实现继承 SubType.prototype.getSubValue = function() { return this.subproperty; var instance1 = new SubType(); var instance2 = new SubType(); instance1.property.push(4); console.log(instance1.property); // [1,2,3,4] console.log(instance2.property); // [1,2,3,4]
我们修改一处的实例属性,两个实例的属性都会被修改,因为这个属性是共享的,这也是原型链继承的缺点。
2.构造函数继承function SuperType(name) { this.name = name; this.numbers = [1,2,3]; function SubType() { SuperType.call(this,"Nicholas"); this.age = 29; var instance1 = new SubType(); var instance2 = new SubType(); instance1.property.push(4); console.log(instance1.name); // Nicholas console.log(instance1.age); // 29 console.log(instance1.numbers); // [1,2,3,4] console.log(instance2.numbers); // [1,2,3]
在子类中调用父类的构造函数,每次实例化时都会新建父类的属性放在新实例中,因此每个实例中的属性都是不一样的,改变一个实例的值不会造成另一个实例的值改变。这个继承方式的缺点是方法的定义不能复用。
3.组合继承这个方法将原型链继承和构造函数继承结合到一起,融合了他们各自的优点。
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; SubType.prototype = new SuperType(); SubType.prototype.constructor = SubType; SubType.prototype.sayAge = function() { console.log(this.age); var instance1 = new SubType("Nicholas", 29); var instance2 =new SubType("Greg", 27); instance1.colors.push("black"); console.log(instance1.colors); // red,blue,green,black console.log(instance2.colors); // red,blue,green instance1.sayName(); // Nicholas instance2.sayName(); // Greg instance1.sayAge(); // 29 instance2.sayAge(); // 274.class继承
ES6中可以通过class创建对象,通过关键字extends继承。
class Point { constructor(x, y) { this.x = x; this.y = y; class ColorPoint extends Point { constructor(x, y, color) { this.color = color; // ReferenceError super(x, y); this.color = color; // 正确
在ES6的继承中,子类一定要重写父类的构造函授的方法,否则会报错。
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《》
希望本文所述对大家JavaScript程序设计有所帮助。
Copyright © 2002-2020 在线网页制作_建网页_个人简介网页制作_简单网页_建立网页 版权所有 (网站地图) 粤ICP备10235580号