Using new in an anonymous object with prototype property?

Can i do:

var foo = new Foo; 

from:

 var Foo = { prototype : { } }; 

As I would do with:

 var Foo = function() { }; 

?

Thanks for your help.

+4
source share
5 answers

No, you can’t.

The fact is that the prototype property is a constructor property, in this case Foo . If you create an object using a syntax literal such as

 var foo = { prototype: {} }; 

you have a property assigned to an object, not a constructor.

This is a difference, and therefore automatic search for a prototype object will not work when using this literal.

If you want to work with a prototype, you must 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 doesn't work if you try to assign the constructor object to an object in literal syntax: it only works again when using true prototyping.

Hope this helps.

+5
source

Not. The value after the new operator must be something constructive (an object with [[construct]] ), like functions. You cannot use arbitrary objects.

To inherit from an arbitrary object, use Object.create :

 var fooProto = { … }; var foo = Object.create(fooProto); 
+2
source

No, "n new X X must evaluate the function.

Thanks for your reply. Can I manually add it to the constructor, for example: {constructor: {prototype: {}}}; I don’t need to do this, I just want to understand the mechanics.

The mechanic is that it must be a function, the .constructor or .prototype do not matter at all, and you can actually new X , even if you delete .prototype X property - all you literally need is a function X
0
source

NOT. As in

 var Foo = { prototype : { } }; 

Foo is an object, not a function. You can only do "new" functions

0
source

A little hint:

 function Fun() {}; var anonym = {}; var fun = new Fun; anonym.prototype.p = function() {}; Fun.prototype.p = function(){}; 'p' in anonym; // false 'p' in fun; // true (engine looks for properties in constructor prototype object) anonym.constructor.prototype.p = function() {}; 'p' in anonym; // true 
0
source

Source: https://habr.com/ru/post/1495523/


All Articles