深入理解Object.create

litongqian發表於2018-03-05

再具體講解之前我們先看一個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

上面程式碼中,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的繼承程式碼了!