前端開發者進階之ECMAScript新特性【一】--Object.create


Object.create(prototype, descriptors) :創建一個具有指定原型且可選擇性地包含指定屬性的對象

參數:
prototype 必需。  要用作原型的對象。 可以為 null。
descriptors 可選。 包含一個或多個屬性描述符的 JavaScript 對象。
“數據屬性”是可獲取且可設置值的屬性。 數據屬性描述符包含 value 特性,以及 writable、enumerable 和 configurable 特性。

如果未指定最后三個特性,則它們默認為 false。 只要檢索或設置該值,“訪問器屬性”就會調用用戶提供的函數。 訪問器屬性描述符包含 set 特性和/或 get 特性。

var pt = {
        say : function(){
            console.log('saying!');    
        }
    }
    
    var o = Object.create(pt);
    
    console.log('say' in o); // true
    console.log(o.hasOwnProperty('say')); // false

如果prototype傳入的是null,創建一個沒有原型鏈的空對象。

var o1 = Object.create(null);
console.dir(o1); // object[ No Properties ]

 當然,可以創建沒有原型鏈的但帶descriptors的對象;

var o2 = Object.create(null, {
        size: {
            value: "large",
            enumerable: true
        },
        shape: {
            value: "round",
            enumerable: true
        }    
    });
    
    console.log(o2.size);    // large
    console.log(o2.shape);     // round
    console.log(Object.getPrototypeOf(o2));     // null

也可以創建帶屬性帶原型鏈的對象:

var pt = {
        say :
function(){
            console.log(
'saying!');   
        }
    }

var
o3 = Object.create(pt, { size: { value: "large", enumerable: true }, shape: { value: "round", enumerable: true } }); console.log(o3.size); // large console.log(o3.shape); // round console.log(Object.getPrototypeOf(o3)); // {say:...}

 最重要的是實現繼承,看下面實例:

//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);
        
        var rect = new Rectangle();

        console.log(rect instanceof Rectangle); //true.
        console.log(rect instanceof Shape); //true.
        
        rect.move(); //"Shape moved."

 不支持瀏覽器的兼容實現:

1、簡單實現,也是最常見的實現方式,沒有實現第二個參數的功能:

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}

2、復雜實現,實現第二個參數的大部分功能:

if (!Object.create) {

    // Contributed by Brandon Benvie, October, 2012
    var createEmpty;
    var supportsProto = Object.prototype.__proto__ === null;
    if (supportsProto || typeof document == 'undefined') {
        createEmpty = function () {
            return { "__proto__": null };
        };
    } else {
        createEmpty = function () {
            var iframe = document.createElement('iframe');
            var parent = document.body || document.documentElement;
            iframe.style.display = 'none';
            parent.appendChild(iframe);
            iframe.src = 'javascript:';
            var empty = iframe.contentWindow.Object.prototype;
            parent.removeChild(iframe);
            iframe = null;
            delete empty.constructor;
            delete empty.hasOwnProperty;
            delete empty.propertyIsEnumerable;
            delete empty.isPrototypeOf;
            delete empty.toLocaleString;
            delete empty.toString;
            delete empty.valueOf;
            empty.__proto__ = null;

            function Empty() {}
            Empty.prototype = empty;
            // short-circuit future calls
            createEmpty = function () {
                return new Empty();
            };
            return new Empty();
        };
    }

    Object.create = function create(prototype, properties) {

        var object;
        function Type() {}  // An empty constructor.

        if (prototype === null) {
            object = createEmpty();
        } else {
            if (typeof prototype !== "object" && typeof prototype !== "function") {

                throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome
            }
            Type.prototype = prototype;
            object = new Type();

            object.__proto__ = prototype;
        }

        if (properties !== void 0) {
            Object.defineProperties(object, properties);
        }

        return object;
    };
}

參考:

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/create

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/defineProperty

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/defineProperties

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

https://github.com/kriskowal/es5-shim/blob/master/es5-sham.js


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM