1

while reading a book (JavaScript : The definitive Guide) i have found a piece of code that implement Object.create in ES3:

// 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.
}

and there is my implementation :

function inherit(proto) {
        var o = {};

        if(typeof proto != "function" && typeof proto != "object")
                throw TypeError();

        o.prototype = proto;
        return o;
}
  • i Don't understand why the book author have created a function and use it as constructor to return the new object that have a prototype p, while its possible to simply o.prototype = proto
KarimS
  • 3,812
  • 9
  • 41
  • 64

0 Answers0