不看会后悔的对象继承方式

11次阅读

共计 1480 个字符,预计需要花费 4 分钟才能阅读完成。

转载请注明出处

JavaScript 中,对象的继承大致分为 5 种。分别是:

  • 构造函数绑定
  • 原型链继承
  • 拷贝继承
  • ES6 的 Class
  • 经典继承(利用空对象作为中介)

经典继承适用于对象和对象之间的继承

下面是详细介绍:

先定义两个构造函数 Animal 和 Cat

function Animal(){this.species = "动物";}

function Cat(name,color){

    this.name = name;

    this.color = color;

}

上面定义了两个函数,一个是 Cat,一个是 Animal,怎么样才能是 Cat 继承 Animal。

1. 构造函数绑定

使用 call 或 apply 方法,将父对象的构造函数绑定在子对象上。

function Cat(name,color){Animal.apply(this, arguments);

    this.name = name;

    this.color = color;

}

var cat1 = new Cat("大毛","黄色");

alert(cat1.species); // 动物

2. 原型链继承

直接使用 prototype 属性,把 Cat.prototype 的原型设置为 Animal 实例或者 Animal.prototype

// 指向 Animal 实例
Object.setPrototypeOf(Cat.prototype, new Animal())
/*
* 上一行也可以这么写
* Cat.prototype.__proto__ = new Animal();
*/
var cat1 = new Cat("大毛","黄色");

alert(cat1.species); // 动物


// 指向 Animal.prototype
// 这里要对 Animal 做一个改进,把不变的属性放到 prototype 中去
function Animal(){}

Animal.prototype.species = "动物";

Object.setPrototypeOf(Cat.prototype, Animal.prototype)
/*
* 上一行也可以这么写
* Cat.prototype.__proto__ = Animal.prototype
*/

var cat1 = new Cat("大毛","黄色");

alert(cat1.species); // 动物

3. 拷贝继承

把父对象的所有属性和方法,拷贝进子对象。

var p = Parent.prototype;

var c = Child.prototype;

for (var i in p) {c[i] = p[i];

}

4. Class 继承

Class 可以通过 extends 关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

// 在 constructor 中调用 super()
class Parent {constructor (x, y) {
        this.x = x
        this.y = y
    }
    test = '测试'
}
class Child extends Parent {constructor (x, y, z) {super(x,y)
        this.z = z
    }
}
let child = new Child(1, 2, 3)
child.test  // 测试

5. 经典继承(利用空对象作为中介)

适用于对象和对象之间的继承

let a = {test: 'name'}
// 通过对象字面量创建的对象没有原型
// a.prototype === undefined
// a
let b = {name: 'test'}
function C() {}
C.prototype = a
b = new C()
b.test  // name

对象的继承除了上面常见的 5 种方式外,你也可以把他们组合来实现继承。

参考资料

  • 构造函数的继承
  • 非构造函数的继承

欢迎浏览我的个人网站

正文完
 0