通过原型继承创建一个新对象

// 通过原型继承创建一个新对象
function inherit(p){
if (p == null) throw TypeError();//p是一个对象,但不能是null
if(Object.create) //如果object.create()存在
return Object.create(p); //直接使用它
var t = typeof p;//否则进行进一步检测
if (t !== "object" && t !== 'function') throw TypeError();
function f(){};//将其原型属性设置为p
f.prototype = p;//使用f()创建p的继承对象
return new f();
}

例如:
var o = {}
o.x = 1;//给o定义一个属性
var p = inherit(o);//p继承o和Object.prototype
console.log(p);
p.y =2;
var q = inherit(p);//q继承p、o、Object.prototype
q.z = 3;
console.log(q.x + q.y + q.z);//6
var s = q.toString();
console.log(s);//[object Object]

猜你喜欢

转载自www.cnblogs.com/studyh5/p/9220596.html