Can i do :
var foo = new Foo;
with :
var Foo = { prototype : { } };
As i would do with :
var Foo = function() { };
?
Thanks for your help.
Can i do :
var foo = new Foo;
with :
var Foo = { prototype : { } };
As i would do with :
var Foo = function() { };
?
Thanks for your help.
Share Improve this question edited Aug 6, 2013 at 13:46 Virus721 asked Aug 6, 2013 at 11:53 Virus721Virus721 8,34514 gold badges76 silver badges129 bronze badges 1- hmm is there some problem behind this? – Esailija Commented Aug 6, 2013 at 11:58
5 Answers
Reset to default 5No, 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 ments, 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);
NO. As in
var Foo = { prototype : { } };
Foo is an object not a function. You can do "new" only on function
No, ìn new X
X
must evaluate to a function.
Thanks for your answer. Could i manually add it to the constructor, like : { constructor : { prototype: {} } }; I don't need to do it, just want to understand the mechanics.
The mechanic is that it must be a function, the .constructor
or .prototype
properties do not matter at all and you can in fact new X
even if you delete
the .prototype
property of X
- all you need literally need is for X
to be a function.
Small 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's prototype object)
anonym.constructor.prototype.p = function() {};
'p' in anonym; // true