Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using new on an anonymous object with a prototype property?

Can i do :

var foo = new Foo;

with :

var Foo = { prototype : { } };

As i would do with :

var Foo = function() { };

?

Thanks for your help.

like image 846
Virus721 Avatar asked Mar 22 '23 21:03

Virus721


2 Answers

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.

like image 78
Golo Roden Avatar answered Apr 05 '23 21:04

Golo Roden


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);
like image 26
Bergi Avatar answered Apr 05 '23 19:04

Bergi