Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的proto

  1. const person = {
  2. isHuman: false,
  3. printIntroduction: function() {
  4. console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  5. }
  6. };
  7. const me = Object.create(person);
  8. me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
  9. me.isHuman = true; // inherited properties can be overwritten
  10. me.printIntroduction();
  11. // expected output: "My name is Matthew. Am I human? true"

语法

Object.create(proto,[propertiesObject])

参数

proto
新创建对象的原型对象。
propertiesObject
可选。需要传入一个对象,该对象的属性类型参照Object.defineProperties()的第二个参数。如果该参数被指定且不为 undefined,该传入对象的自有可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)将为新创建的对象添加指定的属性值和对应的属性描述符。

返回值

一个新对象,带着指定的原型对象和属性。

例外

如果propertiesObject参数是 null 或非原始包装对象,则抛出一个 TypeError 异常。

1.call 继承不用object.create

react.Name() 生效
react.move(1,1) 失效
原因: react.Name()不是原型中的方法,是普通方法

  1. // Shape - 父类(superclass)
  2. function Shape() {
  3. this.x = 0;
  4. this.y = 0;
  5. this.Name = function Introduce(){ console.log("i am not prototype.method") }
  6. }
  7. // 父类的方法
  8. Shape.prototype.move = function(x, y) {
  9. this.x += x;
  10. this.y += y;
  11. console.info('Shape moved.');
  12. };
  13. // Rectangle - 子类(subclass)
  14. function Rectangle() {
  15. Shape.call(this); // call super constructor.
  16. }
  17. var rect = new Rectangle();
  18. console.log('Is rect an instance of Rectangle?',
  19. rect instanceof Rectangle); // true
  20. console.log('Is rect an instance of Shape?',
  21. rect instanceof Shape); // true
  22. new Shape().Name();
  23. rect.Name()
  24. rect.move(1, 1); // ---> 报错 ,原型没有被继承

2.只使用Object.create(Shape.prototype);

普通方法react.Name失效 —》TypeError: rect.Name is not a function
原因:只进行了原型继承

  1. // Shape - 父类(superclass)
  2. function Shape() {
  3. this.x = 0;
  4. this.y = 0;
  5. this.Name = function Introduce(){ console.log("i am not prototype.method") }
  6. }
  7. // 父类的方法
  8. Shape.prototype.move = function(x, y) {
  9. this.x += x;
  10. this.y += y;
  11. console.info('Shape moved.');
  12. };
  13. // Rectangle - 子类(subclass)
  14. function Rectangle() {
  15. //删除原先的Shape.call(this)
  16. }
  17. Rectangle.prototype = Object.create(Shape.prototype);
  18. Rectangle.prototype.constructor = Rectangle;
  19. var rect = new Rectangle();
  20. rect.Name()
  21. rect.move(1, 1); // Outputs, 'Shape moved.'

3.一起使用

全部生效
原因:原型和对象都一起继承了过来

// Shape - 父类(superclass)
function Shape() {
  this.x = 0;
  this.y = 0;
  this.Name = function Introduce(){ console.log("i am not prototype.method") }
}

// 父类的方法
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};


// Rectangle - 子类(subclass)
function Rectangle() {
  Shape.call(this);
  //删除原先的Shape.call(this)
}
 Rectangle.prototype = Object.create(Shape.prototype);
 Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();
rect.Name()
rect.move(1, 1); // Outputs, 'Shape moved.'

4. Object.Create 和 Object.Assign()实现混合继承

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
};


5. 使用 Object.create的propertyObject参数

var o;

// 创建一个原型为null的空对象
o = Object.create(null);


o = {};
// 以字面量方式创建的空对象就相当于:
o = Object.create(Object.prototype);


o = Object.create(Object.prototype, {
  // foo会成为所创建对象的数据属性
  foo: {
    writable:true,
    configurable:true,
    value: "hello"
  },
  // bar会成为所创建对象的访问器属性
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) {
      console.log("Setting `o.bar` to", value);
    }
  }
});


function Constructor(){}
o = new Constructor();
// 上面的一句就相当于:
o = Object.create(Constructor.prototype);
// 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码


// 创建一个以另一个空对象为原型,且拥有一个属性p的对象
o = Object.create({}, { p: { value: 42 } })

// 省略了的属性特性默认为false,所以属性p是不可写,不可枚举,不可配置的:
o.p = 24
o.p
//42

o.q = 12
for (var prop in o) {
   console.log(prop)
}
//"q"

delete o.p
//false

//创建一个可写的,可枚举的,可配置的属性p
o2 = Object.create({}, {
  p: {
    value: 42,
    writable: true,
    enumerable: true,
    configurable: true
  }
});

5.1 我的Demo

代码:

var o 
o = Object.create(Object.prototype, {
  // foo会成为所创建对象的数据属性
  foo: {
    writable:true,
    configurable:true,
    value: "hello"
  },
  // bar会成为所创建对象的访问器属性
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) {
      console.log("Setting `o.bar` to", value);
    }
  },

    h :{
        configurable:true,
        get :function() { 
            return h 
        },
        set :function(value) { h = value  },
    }
});

console.log( o.foo)
console.log(o.bar)
o.bar= 2

o.h =3
console.log(o.h)

结果:
对于h属性来说必须先set 后get 不然就会报错:ReferenceError: h is not defined

hello
10
Setting `o.bar` to 2
3

6.Object.create()的本质

function F() {}
F.prototype = proto;

if (typeof Object.create !== "function") {
    Object.create = function (proto, propertiesObject) {
        if (typeof proto !== 'object' && typeof proto !== 'function') {
            throw new TypeError('Object prototype may only be an Object: ' + proto);
        } else if (proto === null) {
            throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
        }

        if (typeof propertiesObject !== 'undefined') throw new Error("This browser's implementation of Object.create is a shim and doesn't support a second argument.");

        function F() {}
        F.prototype = proto;

        return new F();
    };
}