1. 程式人生 > >通過原型繼承建立新物件

通過原型繼承建立新物件


window.onload = function(){

var a = new Object();
a.x = 1;
a.y = 2;

// var b = inherit({x:4,y:2})
var b = inherit(a); 
console.log(b); // object物件
console.log(b.x); // 1
}


// 通過原型繼承建立新物件
 function inherit(obj){
   if(obj == null) throw TypeError();
   if(Object.create){
     return Object.create(obj);
   }
   var
t = typeof obj; if(t !== 'object' && t !== "function") throw TypeError(); function newObj(){}; newObj.prototype = obj; return new newObj(); }