Hi_World Hi_World -3 years ago 94
Javascript Question

JavaScript: use an object returned by function without object of object

I am new in JavaScript/jQuery. Wondering if there is any better way to return an object by a function.

//this is the Object creator.
function makeNewPlayer(name, score) {
var player = {};
player.name = name;
player.score = score;

return player;
};


This is how I use the function.

var player_info = makeNewPlayer('Bob' ,100);


However, when I use the object, I need to call it like this:

player_info.player.name
player_info.player.score


It looks stupid, any way to use the object directly like this?

player_info.name
player_info.score


edit:

As I don't know how many object will be created by the function.
Let say there is a for loop to make score_1, score_2 etc.

function makeNewPlayer(name, score) {
var player = {};
player.name = name;

for(i=0, i<score_no, i++){
eval("player.score_" + i) = score[i];
};

return player;
};

Answer Source

Use new.

I copied some text from my blog that happened to resolve your doubts:

A constructor is a special function used for creating an object:

Example:

function StarkIndustries(name, birth) {
  this.name = name;
  this.birth = birth;
}
var iron1 = new StarkIndustries('iron01', 2017);
var iron2 = new StarkIndustries('iron02', 2017);
alert(iron1.name);
alert(iron2.name);

Result:

iron01
iron02

By adding new before a function, the function is turned into a constructor that constructs an object.

But it is dangerous to call a function designed as a constructor without new, because it will modify the global object window. So sanity check inside the constructor is required:

if (!(this instanceof StarkIndustries)) {
  warn("StarkIndustries is a constructor and should be called with `new`");
}

Back to your code, it should be:

function makeNewPlayer(name, score) {
    this.name = name
    this.score = score
};

var iron1 = new makeNewPlayer('iron01', 2017);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download