美文网首页
用 Object.create实现类式继承

用 Object.create实现类式继承

作者: anefish | 来源:发表于2017-11-16 16:23 被阅读0次

下面的例子演示了如何使用Object.create()来实现类式继承。这是一个所有版本JavaScript都支持的单继承。

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

如果你希望能继承到多个对象,则可以使用混入的方式。

function MyClass() {
     SuperClass.call(this);
     OtherSuperClass.call(this);
}

// inherit one class
MyClass.prototype = Object.create(SuperClass.prototype);
// mixin another
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// re-assign constructor
MyClass.prototype.constructor = MyClass;

MyClass.prototype.myMethod = function() {
     // do a thing
};

转自MDN

相关文章

  • Object.create实现类继承和克隆对象

    Object.create实现类继承 先看不用Object.create来实现继承 效果: 用Object.cre...

  • 用 Object.create实现类式继承

    下面的例子演示了如何使用Object.create()来实现类式继承。这是一个所有版本JavaScript都支持的...

  • 用 Object.create 实现类式继承

    Object.create 官方文档:https://developer.mozilla.org/zh-CN/do...

  • javascript 使用Object.create实现类式继承

    Object.create()方法创建一个拥有指定原型和若干个指定属性的对象。 什么是prototype: 每个函...

  • JavaScript类的继承

    Object.create() 实现单继承 Object.assign() 实现多继承 Object.assign...

  • js面向对象实现面向对象(二)

    上一篇讲到js实现对类对封装,本篇介绍类的继承,多态。 类的继承 类式继承 类式继承方式是将父类的实例赋在子类的原...

  • 5. oop继承

    JavaScript 继承实现方式 A. 类式继承 所谓类式继承,就是将子类的原型指向父类的一个实例。这样优缺点就...

  • js 继承

    Object.create()实现经典继承 me和person都是Object对象,me继承了person的所有属...

  • js实现继承

    1、使用ES6的方式 2、使用原型链组合继承 3、使用Object.create实现继承

  • JS~继承

    JS中的继承按照是否使用了object.create 可分为两类(object.create 是ES5新增的方法)...

网友评论

      本文标题:用 Object.create实现类式继承

      本文链接:https://www.haomeiwen.com/subject/tbalvxtx.html