DaMaxContent DaMaxContent - 3 months ago 12
Javascript Question

Constructor Behavior in JS

I have 4 things (below) I would like to know about the concepts of functions (specifically Object Constructors, Function Expressions, and Nested Functions) when the concepts are mixed are:


  • Can an object constructor be conditionally a regular function and a constructor?



(maybe like this? does this work the way I'm asking it too?)

function whatAmI( option ){
if( option === 1 ){ // function is a constructor
this.prop1 = "lorem ipsum";
this.prop2 = "lorem ipsum";
}else{ // function is a function
return "hello there";
}
}
var object = new whatAmI(1);
var string = whatAmI(0);



  • Can an object constructor have nested functions (that are not methods)?



(maybe like this? does this work the way I'm asking it too?)

function constructor(){
this.someMethod = function(){ ... } //method of an object
function nestedFunction(){ //nested function inside constructor that is not a method
alert("constructed");
}
nestedFunction();
}



  • Can an object constructor be an anonymous immediately-invoked function expression?



(maybe like this? does this work the way I'm asking it too?) (this one is just a mere curiousity)

var obj = ( function( arg ){ this.stuff = arg } )( "argument as a string" );



  • What does the
    return
    keyword do in a simple object constructor?



(like this:)

function Constructor() {
this.stuff = "stuff";
this.otherStuff = "stuff";
return "successfully constructed";
}
var obj = new Constructor();



  • for the example above, if I instead called
    var obj = Constructor()
    inside the DOM
    window
    what would
    this
    be?



note: I am looking for an explanation as to why or why not as opposed to a simple "yes" or "no"

Answer

A constructor function is just a function nothing more than that. Likewise any function you invoke with the new keyword becomes a constructor.

function whatAmI(){
    this.prop1 = "lorem ipsum";
    this.prop2 = "lorem ipsum";
    return "hello there";
}
var object = new whatAmI();
var string = whatAmI();
console.log(object);
console.log(string);

No need for options whatsoever. As you see it can both instantiate an object if called with new or can return a string if not.

As per @torazaburo's comment if the returned value is an object it will override the properties defined by this and the newly constructed object will be the returned one. Our constructor function will then work like a factory.

function whatAmI(){
        this.prop1 = "lorem ipsum";
        this.prop2 = "lorem ipsum";
        return {a:100};
    }
    var o1 = new whatAmI();
    var o2 = whatAmI();
    console.log(o1);
    console.log(o2);

If the returned value is primitive type it should work as expected though.

Comments