0

Okay, so I've been reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new And find myself writing a bunch of object construction code in a class sort of scheme.

To maintain backward compatibility I haven't been using 'class' keyword/syntax much.

You may have seen this before:

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}
//Usage: var carinstance = new Car("blah","blah","blah");

But I've found that this works quite well for my use (found by accident):

function Player (name) {
    var p = {
        name : name,
        age : 18
    };
    return p;
}
//Usage: var person = new Player("Jon");

I know it works, as I've used it. I just don't know if this is proper.

For example, I can use the same code w/o 'new' keyword (same result):

var person = Player("Jon");

But I cannot do the same with the first specification (using 'this' keyword in a function):

var car = Car("blah","blah","blah"); //car == undefined

I don't really know how to google this, or what to call it. I was hard enough trying to figure out what title this question should have.

I guess a more definitive way to put the question: Are the results I'm getting just a quark of javascript, browser engine, etc? Or is this a solid way to make a constructor function?

2
  • 2
    Your first approach uses constructor as you are using this and you will have to use new or Object.create to create object. In your second approach, you are returning an object but it does not uses a constructor. 1 major difference will come into play when you start using prototype. An object created with new will have your defined prototype and other one will only have default prototype Commented Jul 25, 2017 at 5:34
  • 1
    Yes, this is a quark of how this works in JavaScript. Not affiliated to the below channels, but these are great resources to learn about what's going on here! The new keyword .... "this & Object Prototypes" Commented Jul 25, 2017 at 5:36

2 Answers 2

0

Because in Player function, it returns p object. So, if you use new operator call Player function, it will be p object but not the default created obj.Of course, it will also return p object when you call Player in general. However, in Car function, it doesn't return an object.Therefore, when you use new operator call Car function, it will return the default created an object and it will return undefined with calling Car function in general.

you can refer:

usage of new operator

Sign up to request clarification or add additional context in comments.

Comments

0

Do the following.

function Car(make, model, year) {
    if ( !(this instanceof Car) )
      return new Car(make, model, year);
    this.make = make;
    this.model = model;
    this.year = year;
}

and then you can call it without new.

Comments

Your Answer

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