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