深入理解Object.create

8,802 阅读3分钟

再具体讲解之前我们先看一个ES6实现继承的例子

class Point {
    static NAME='point';

    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
  
    outPoint(){
        console.log('point:'+this.x+this.y);
    }
}

class ColorPoint extends Point {
    static COLOR_NAME='ColorPoint';

    constructor(x, y, color) {
        super(x, y);    
        this.color = color;
    }

    outColorPoint(){
        console.log('ColorPoint:'+this.x+this.y+this.color);
    }
}

现在将其通过babel转换为es5;

'use strict';

var _createClass = function() {
    function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }
    return function(Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
    };
} ();

function _possibleConstructorReturn(self, call) {
    if (!self) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return call && (typeof call === "object" || typeof call === "function") ? call: self;
}

function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

function _classCallCheck(instance, Constructor) {
    if (! (instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}

var Point = function() {
    function Point(x, y) {
        _classCallCheck(this, Point);

        this.x = x;
        this.y = y;
    }

    _createClass(Point, [{
        key: 'outPoint',
        value: function outPoint() {
            console.log('point:' + this.x + this.y);
        }
    }]);

    return Point;
} ();

Point.NAME = 'point';

var ColorPoint = function(_Point) {
    _inherits(ColorPoint, _Point);

    function ColorPoint(x, y, color) {
        _classCallCheck(this, ColorPoint);

        var _this = _possibleConstructorReturn(this, (ColorPoint.__proto__ || Object.getPrototypeOf(ColorPoint)).call(this, x, y));

        _this.color = color;
        return _this;
    }

    _createClass(ColorPoint, [{
        key: 'outColorPoint',
        value: function outColorPoint() {
            console.log('ColorPoint:' + this.x + this.y + this.color);
        }
    }]);

    return ColorPoint;
} (Point);

ColorPoint.COLOR_NAME = 'ColorPoint';

看着还是比较凌乱,我们将代码简化,去掉验证信息,_createClass使用prototype代替,简化后代码

'use strict';
function _inherits(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    subClass.__proto__ = superClass;
}
var Point = function(x, y) {
    this.x = x;
    this.y = y;
}
Point.prototype.outPoint = function outPoint() {
    console.log('point:' + this.x + this.y);
}

Point.NAME = 'point';

var ColorPoint = function(_Point) {
    _inherits(ColorPoint, _Point);

    function ColorPoint(x, y, color) {
        ColorPoint.__proto__.call(this,x,y);
        this.color = color;
    }
    ColorPoint.prototype.outColorPoint = function() {
        console.log('ColorPoint:' + this.x + this.y + this.color);
    }
    return ColorPoint;
} (Point);

ColorPoint.COLOR_NAME = 'ColorPoint';    

简化后的代码可以看到_inherits 方法是实现父类原型对象的继承,ColorPoint.__proto__上应用了父类构造函数Point,使用ColorPoint.__proto__.call(this,x,y),使用call继承父类构造器中的属性

下面聊一聊Object.create

function _inherits(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype, {
        constructor: {
            value: subClass,
            enumerable: false,
            writable: true,
            configurable: true
        }
    });
    subClass.__proto__ = superClass;
}

使用实例对象,生成另一个实例对象!


上面代码中,Object.create方法以A对象为原型,生成了B对象。B继承了A的所有属性和方法。

实际上,Object.create方法可以用下面的代码代替。

Object.create = function (obj) {
    function F() {}
    F.prototype = obj;
    return new F();
  };

上面代码表明,Object.create方法的实质是新建一个空的构造函数F,然后让F.prototype属性指向参数对象obj,最后返回一个F的实例,从而实现让该实例继承obj的属性。

或者

Object.create = function (obj) {
    var B={};
    Object.setPrototypeOf(B,obj);
    return B;  
};

更直观点

Object.create = function (obj) {
    var B={};
    B.__proto__=obj;
    return B;  
};

如果想要生成一个不继承任何属性(比如没有toStringvalueOf方法)的对象,可以将Object.create的参数设为null

var obj = Object.create(null);

object.create方法生成的新对象,动态继承了原型。在原型上添加或修改任何方法,会立刻反映在新对象之上。

var obj1 = { p: 1 };
var obj2 = Object.create(obj1);

obj1.p = 2;
obj2.p // 2

上面代码中,修改对象原型obj1会影响到实例对象obj2

Object.create的第二个参数

除了对象的原型,Object.create方法还可以接受第二个参数。该参数是一个属性描述对象,它所描述的对象属性,会添加到实例对象,作为该对象自身的属性。

var obj = Object.create({}, {
  p1: {
    value: 123,
    enumerable: true,
    configurable: true,
    writable: true,
  },
  p2: {
    value: 'abc',
    enumerable: true,
    configurable: true,
    writable: true,
  }
});

// 等同于
var obj = Object.create({});
obj.p1 = 123;
obj.p2 = 'abc';

理解了Object.create,就可以轻松去理解ES6转ES5的继承代码了!