user8112809
user8112809

Reputation:

javascript new object constructor function alternative proper?

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?

Upvotes: 0

Views: 923

Answers (2)

Kermit
Kermit

Reputation: 1062

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

Upvotes: 0

Lime
Lime

Reputation: 13569

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.

Upvotes: 0

Related Questions