Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid Object Constructors

Tags:

javascript

which of the following are valid object constructors?

1) var m = function(){}
2) m = function(){}
3) m.prototype.constructor = function(){}
like image 605
coure2011 Avatar asked Mar 11 '26 20:03

coure2011


2 Answers

They all appear to be valid statements that declare an empty function, and assign it to different variables.

Every function in Javascript is both an object itself (or f.prototype wouldn't work) and a potential object constructor. Any function may be called with the new Thingy syntax (or perhaps new m in your example). Or it could be called normally - the only special thing new does is set this to an object derived from f.prototype.

A newly created function has a prototype property that contains a newly minted object ({}), which has no properties except a hidden constructor property pointing at the function (it's a circular reference, actually)

It should be true that:

var m = function(){};
m.prototype.constructor == m;
like image 99
Justin Love Avatar answered Mar 13 '26 09:03

Justin Love


You forgot var m = {};

This is called an object literal.

like image 40
cllpse Avatar answered Mar 13 '26 09:03

cllpse