转载请注明出处javascript
在JavaScript
中,对象的继承大体分为5种。分别是:html
经典继承适用于对象和对象之间的继承java
下面是详细介绍:app
先定义两个构造函数Animal和Cat函数
function Animal(){
this.species = "动物";
}
function Cat(name,color){
this.name = name;
this.color = color;
}
复制代码
上面定义了两个函数,一个是Cat,一个是Animal,怎么样才能是Cat继承Animal。测试
使用call或apply方法,将父对象的构造函数绑定在子对象上。网站
function Cat(name,color){
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); // 动物
复制代码
直接使用prototype属性,把Cat.prototype的原型设置为Animal实例或者Animal.prototypeui
// 指向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); // 动物
复制代码
把父对象的全部属性和方法,拷贝进子对象。this
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
复制代码
Class 能够经过extends
关键字实现继承,这比 ES5 的经过修改原型链实现继承,要清晰和方便不少。spa
// 在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 // 测试
复制代码
适用于对象和对象之间的继承
let a = {
test: 'name'
}
// 经过对象字面量建立的对象没有原型
// a.prototype === undefined
// a
let b = {
name: 'test'
}
function C() {}
C.prototype = a
b = new C()
b.test // name
复制代码
对象的继承除了上面常见的5种方式外,你也能够把他们组合来实现继承。
欢迎浏览个人我的网站