2015-05-28 32 views

回答

7

「替代原型交換」(我懷疑是一個真實的事情開始)是使用一個對象只能分配給它的原型。該變量只能使用一次:

// Naked function reference for surrogate-prototype-swapping. 
var Ctor = function(){}; 

var nativeCreate = Object.create; 

// An internal function for creating a new object that inherits from another. 
var baseCreate = function(prototype) { 
    if (!_.isObject(prototype)) return {}; 

    if (nativeCreate) return nativeCreate(prototype); 

    Ctor.prototype = prototype; 
    var result = new Ctor; 
    Ctor.prototype = null; 
    return result; 
}; 

它是用來做的Object.create一個跨瀏覽器版本。你不能直接創建一個原型對象的新實例,所以你用你的原型對象創建一個臨時對象作爲它的原型,並返回一個新的實例。

+0

你回答了我的問題,但爲了那些追隨者,我打算進一步分解它。如果我錯了,請糾正我。 – user1294511

+0

有趣......但我不明白這是如何需要使用全局函數引用。難道你不能在工廠'baseCreate'中定義'function(){}'? –

+0

@JoelCornett:他們使用'Ctor.prototype = null'的原因相同。它可能跑得更快? – Blender

16

Blender的答案使成爲可能。適用於我的水平。

雖然它不是一個真正的術語,但下面是通過更原始的underscore.js代碼的更完整的評論來替代原型交換的預期含義的細分。

// A function which will be used as a constructor function in order 
// to add a prototype to a new object. There is nothing special about 
// this function, except how it will be used. 
var Ctor = function(){}; 

// Create a shortcut to Object.create if it exists. Otherwise 
// nativeCreate will be undefined 
var nativeCreate = Object.create; 

// An internal function that will use or act as a polyfill for 
// Object.create, with some type checking built in. 
var baseCreate = function(prototype) { 
    // Check if the object passed to baseCreate is actually an object. 
    // Otherwise simply return an object (from an object literal), 
    // because there is not a valid object to inherit from. 
    if (!_.isObject(prototype)) return {}; 

    // If Object.create is implemented then return the value 
    // returned by Object.create when the prototype parameter is 
    // passed into it. If Object.create has already been 
    // implemented there is no need to recreate it. Just return 
    // its return value. 
    if (nativeCreate) return nativeCreate(prototype); 

    // If Object.create is not defined then Ctor comes into play. 
    // The object passed to baseCreate is assigned to the prototype 
    // of Ctor. This means when Ctor is called prototype will be 
    // the prototype assigned to this (the keyword this). 
    Ctor.prototype = prototype; 
    // Because Ctor is called with the new keyword this (the 
    // keyword this) is returned returned by Ctor. Thus, the 
    // variable 'result' is assigned an object with a prototype 
    // equal to baseCreate's parameter 'prototype'. 
    var result = new Ctor; 
    // Then to reset things Ctor.prototype is set to null. 
    Ctor.prototype = null; 
    // The newly created object, whose prototype is the object 
    // passed to baseCreate is returned. 
    return result; 
};