0

So, I have some questions about Objects in JavaScript. The main question I have is about how do Object Constructors work?

I know that they are functions, and that they take advantage of the this keyword.

What I am confused about is below:

This is a simple Object Constructor:

function LulzImObj() {
    this.rofl = "true";
    this.lmao = "maybe";
}

This is a simple Function:

function lmaoIdoDis( dank ) {
    if( dank ){
        return "such wow";
    }else{
        return "rofl. no wow";
    }
}

So, this is what I am confused about (would this behave as a constructor or a function with a return or both)?:

function suchWowObj( dank ) {
    this.rofl = "true";
    this.lmao = "maybe";
    if( dank ){
        this.pepe = function() { return "trulz"; };
        return "such wow";
    }else{
        return "rofl. no wow";
    }
}

context:

var herp = suchWowObj( true );
var derp = new suchWowObj( true );
var snerp = suchWowObj( false );
var werp = new suchWowObj( false );
  • yes, the names are irrelevant –  Aug 14 '16 at 09:33
  • @JaromandaX wait, so know one knows? how? alright, I'll write the script up myself. and post my own answer. I figured this would be an extremely simple question –  Aug 14 '16 at 09:36
  • Constructors are just functions. If you call them without `new`, `this` will be whatever it normally would be in a function called the same way. In this case, that's the global object, or `undefined` if you're in strict mode. If you call a function with `new` and it returns a value, that value overrides the constructed object. If that's what you're asking, please edit your question to say so explicitly and help other people figure it out =) – Ry- Aug 14 '16 at 09:36
  • 2
    @JaromandaX: And yet, testing the above would only give the OP 90% of the story, because he/she never happens to return a non-`null` object from the "constructor," which would alter the behavior of `new`. – T.J. Crowder Aug 14 '16 at 09:38
  • Well, I figured it was a very valid question. What happens when you smash a simple function with a constructor and how does it work in that case? I personally, have a problem with ctrl-c, ctrl-v into jsfiddle. I just thought this was common knowledge... –  Aug 14 '16 at 09:39

0 Answers0