I’m taking some JavaScript/jQuery lessons at codecademy.com. Normally the lessons provide answers or hints, but for this one it doesn’t give any help and I’m a little confused by the instructions.
It says to make the function makeGamePlayer return an object with three keys.
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
}
I’m not sure if i should be doing this
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
}
or something like this
//First, the object creator
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = {
this.name = name;
this.totalScore = totalScore;
this.gamesPlayed = gamesPlayed;
}
}
I have to be able to modify the properties of the object after its created.
In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.
As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.
The code above calls function
makeGamePlayerand stores the returned value in the variableplayer. In this case, you may want to define the function like this:Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of
thisinside the function. In the case above, sincemakeGamePlayeris not called as a method, thethisvalue will be the global object in sloppy mode, or undefined in strict mode.As constructors, you can use the
newoperator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:.prototypeof the constructorthisvalueThe code above creates an instance of
GamePlayerand stores the returned value in the variableplayer. In this case, you may want to define the function like this:By convention, constructor names begin with an uppercase letter.
The advantage of using constructors is that the instances inherit from
GamePlayer.prototype. Then, you can define properties there and make them available in all instances