在阅读一本书(JavaScript:权威指南)时,我发现了一段在ES3中实现 Object.create 的代码:
// inherit() returns a newly created object that inherits properties from the
// prototype object p. It uses the ECMAScript 5 function Object.create() if
// it is defined, and otherwise falls back to an older technique.
function inherit(p) {
if (p == null) throw TypeError(); // p must be a non-null object
if (Object.create)
// If Object.create() is defined...
return Object.create(p);
//
then just use it.
var t = typeof p;
// Otherwise do some more type checking
if (t !== "object" && t !== "function") throw TypeError();
function f() {};
// Define a dummy constructor function.
f.prototype = p;
// Set its prototype property to p.
return new f();
// Use f() to create an "heir" of p.
}
并且有我的实施:
function inherit(proto) {
var o = {};
if(typeof proto != "function" && typeof proto != "object")
throw TypeError();
o.prototype = proto;
return o;
}