11

is this possible?

My thinking: Prototypes are essentially attributes of the Constructor function (whether native Constructor such as Function, String or Object, or your own custom Constructor) and only the 'new' keyword is able to leverage the Constructor and its prototype for object creation

Am I missing something?

1 Answer 1

12

You are right, but now in the ECMAScript 5th Edition, the Object.create method is able to create object instances using another objects as a prototype:

var proto = {foo: 1};
var obj = Object.create(proto);

In the above example, obj will be created and it will contain a reference to proto in the [[Prototype]] internal property, and:

obj.foo; // 1
obj.hasOwnProperty('foo'); // false

This method is from the new specification approved on December 2009, as far I've seen now is available on the Mozilla JavaScript 1.9.3 implementation.

For now you can mimic the behavior of that method by this, as proposed by Douglas Crockford:

if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    function F() {}
    F.prototype = o;
    return new F();
  };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Cornford once proposed a slightly more efficient version of "beget" (btw, originally mentioned by Lasse Nielsen, not Crockford), where "dummy" function (F in your example) is stored in a closure and is then reused. This makes for a more memory (and runtime) efficient implementation. Also note that Crockford's Object.create emulation hardly conforms to ES5 (no support for second argument, no type check of first argument to throw TypeError if it's not an object, etc.). Employ with care ;)
You are a life saver. I have literally been scouring the web for this idea all day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.