Question

Is there any way whatsoever to enable an object to inherit from a prototype (1) without using new, and (2) without using Object.create. (I had a suspicion that new is present inside the Object.create method, but after the Firebug console told me it's native code, well, I have a suspicion it goes native.) When I say "inherit from a prototype" I mean real JavaScript prototypical inheritance (i.e, not just an imitation of it). I know real inheritance when I see it (i.e., the __proto__ property is present, there is a circular reference between the constructor and the prototype, there is an inheritance hierarchy).

My question boils down to: even though 'we barely new ya', are the only two mechanisms for inheritance new and Object.create?

Was it helpful?

Solution

[...] are the only two mechanisms for inheritance new and Object.create?

Yes, they are. At least those are the only ones you should use.

You could directly assign to __proto__, but it is not a standard property yet. More info: MDN - __proto__.

OTHER TIPS

As you might know new and Object.create do a hidden action than we can call setPrototype.

Object.create = function(proto, properties) {
    var obj = {};
    setPrototype(obj, proto);
    Object.defineProperties(obj, properties);
    return obj;
}

function fakeNew(Constructor) {
    var obj = {};
    setPrototype(obj, Constructor.prototype);
    Constructor.call(obj);
    return obj;
}

It's not than "new is inside Object.create" or "Object.create is inside new". Both does the prototype assignation and other actions.

Actually there is a way to implement setPrototype but surely you know it's not standard.

function setPrototype(obj, proto) {
    obj.__proto__ = proto;
}

In order to avoid using the new operator, but still instantiate an object that inherits from a prototype (the prototype of SomeClass), a simple solution is to build a facade constructor function (which uses the new operator behind the scenes):

function SomeClassFacade() {
  return new SomeClass();
}

SomeClass.prototype = {
 /* ... */
};

Since ES6 you can also use Reflect.construct, which basically behaves like the new operator:

function Constructor() {}
var instance = Reflect.construct(Constructor, []);
Object.getPrototypeOf(instance); // Constructor.prototype

If you want something closer to Object.create, ES6 extending classes can also create inheritance, but only from constructors or null:

var obj = (class extends null{}).prototype;
delete obj.constructor;
Object.getPrototypeOf(obj); // null
function Constructor() {}
var obj = (class extends Constructor{}).prototype;
delete obj.constructor;
Object.getPrototypeOf(obj); // Constructor.prototype
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top