当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS中的继承操作实例总结

JS中的继承操作实例总结

2020年06月14日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js中的继承操作。分享给大家供大家参考,具体如下:

1.原型链继承

function supertype() {
  this.property = true; 
}
supertype.prototype.getsupervalue = function() {
  return this.property;
}
function subtype() {
  ths.subproperty = false;
}
subtype.prototype = new supertype();   // 实现继承
subtype.prototype.getsubvalue = function() {
  return this.subproperty;
}
var instance = new subtype();
console.log(instance.getsupervalue());   // true

原理:让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();           // 27 

4.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代码运行工具:测试上述代码运行效果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网