3

which of the following are valid object constructors?

1) var m = function(){}
2) m = function(){}
3) m.prototype.constructor = function(){}
2
  • What are you trying to achieve? Commented Jul 28, 2010 at 7:39
  • 1
    if firebug or any web consoles did not display any error, then all of that are valid.. did you try it? Commented Jul 28, 2010 at 7:42

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

1

You forgot var m = {};

This is called an object literal.

Comments

0

1) var m = function(){}

2) m = function(){}

Are almost same except the first one creates a local scoped function, the second - global. And in order to create an object you can just

var obj = new m();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.