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?
thisand you will have to useneworObject.createto 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 usingprototype. An object created withnewwill have your defined prototype and other one will only have default prototypethisworks 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"