Object.create創建一個擁有指定原型和若干個指定屬性的對象。但是并不是所有瀏覽器都支持,目前IE瀏覽器IE9以上支持。
if (typeof Object.create != 'function') { // PRoduction steps of ECMA-262, Edition 5, 15.2.3.5 // Reference: http://es5.github.io/#x15.2.3.5 Object.create = (function() { //為了節省內存,使用一個共享的構造器 function Temp() {} // 使用 Object.prototype.hasOwnProperty 更安全的引用 var hasOwn = Object.prototype.hasOwnProperty; return function (O) { // 1. 如果 O 不是 Object 或 null,拋出一個 TypeError 異常。 if (typeof O != 'object') { throw TypeError('Object prototype may only be an Object or null'); } // 2. 使創建的一個新的對象為 obj ,就和通過 // new Object() 表達式創建一個新對象一樣, // Object是標準內置的構造器名 // 3. 設置 obj 的內部屬性 [[Prototype]] 為 O。 Temp.prototype = O; var obj = new Temp(); Temp.prototype = null; // 不要保持一個 O 的雜散引用(a stray reference)... // 4. 如果存在參數 Properties ,而不是 undefined , // 那么就把參數的自身屬性添加到 obj 上,就像調用 // 攜帶obj ,Properties兩個參數的標準內置函數 // Object.defineProperties() 一樣。 if (arguments.length > 1) { // Object.defineProperties does ToObject on its first argument. var Properties = Object(arguments[1]); for (var prop in Properties) { if (hasOwn.call(Properties, prop)) { obj[prop] = Properties[prop]; } } } // 5. 返回 obj return obj; }; })();}https://developer.mozilla.org/zh-CN/docs/Web/javaScript/Reference/Global_Objects/Object/create
新聞熱點
疑難解答