Can i do :
var foo = new Foo;
with :
var Foo = { prototype : { } };
As i would do with :
var Foo = function() { };
?
Thanks for your help.
No, you can't.
The point is that the prototype
property is a property of the constructor, in this case Foo
. If you create an object using literal syntax such as
var foo = { prototype: {} };
you have the property assigned to the object, not the constructor.
That's a difference, and hence automatic lookup on the prototype object won't work when using this literal syntax.
If you want to work with the prototype, you HAVE to use the constructor syntax as follows:
var Foo = function () {};
Foo.prototype.foo = 'bar';
var foo = new Foo();
console.log(foo.foo); // => 'bar'
As discussed in the comments, it also does not work if you try to assign a constructor
property to the object in literal syntax: It again only works when using true prototyping.
Hope this helps.
No. The value after the new
operator must be something constructable (an object with [[construct]]
), like functions are. You cannot use arbitrary objects.
To inherit from an arbitrary object, use Object.create
:
var fooProto = { … };
var foo = Object.create(fooProto);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With