Object.create

2020-12-07  本文已影响0人  如果俞天阳会飞

语法Object.create(proto,[propertiesObject])

proto
新创建对象的原型对象

propertiesObject : 可选。 添加到新创建对象的可枚举属性(即其自身的属性,而不是原型链上的枚举属性)对象的属性描述符以及相应的属性名称。这些属性对应Object.defineProperties()的第二个参数

  const person = {
    isHuman: false,
    printIntroduce() {
      console.log(`my name is ${this.name}`)
    }
  };

  const me = Object.create(person);
  me.name = 'tom';
  me.printIntroduce();
image.png

person对象, 被赋值到 新建对象 me 的原型对象上

用 Object.create实现类式继承

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

// 父类的方法
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.
}

// 子类续承父类
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

rect.move(1, 1); // Outputs, 'Shape moved.'

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

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

// 继承一个类
MyClass.prototype = Object.create(SuperClass.prototype);
// 混合其它
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// 重新指定constructor
MyClass.prototype.constructor = MyClass;

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

Object.create() 用第二个参数

添加到新创建对象的可枚举属性(即其自身的属性,而不是原型链上的枚举属性)对象的属性描述符以及相应的属性名称

const obj = Object.create(Object.prototype, {
      name: {
        value: "hello"
      },
  })
  console.log(obj)
image.png
上一篇 下一篇

猜你喜欢

热点阅读