Hi,
For step 7, to add a .addPlayer() method to the team object, I thought this would work but it gave me a syntax error. Can someone please explain why? Thank you
Here’s the link to the project:
https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-22-javascript-syntax-part-ii/modules/wdcp-22-learn-javascript-syntax-objects/projects/team-stats
Edit: I watched the walkthrough video but I don’t understand why ‘this’ keyword is not used in this situation. Aren’t we supposed to use ‘this’ to reference to calling object (team) here?
Below is my code:
const team = {
_players: [
{ firstName: "Pete", lastName: "Wheeler", age: 54 },
{ fistName: "Thomas", lastName: "Williams", age: 36 },
{ firstName: "Ryan", lastName: "Reynolds", age: 32 },
],
_games: [
{ opponent: "Jets", teamPoints: 32, opponentPoints: 40 },
{ opponent: "Giants", teamPoints: 45, opponentPoints: 12 },
{ opponent: "Eagles", teamPoints: 31, opponentPoints: 50 },
],
addPlayer(newFirstName, newLastName, newAge) {
let player = {
this._players.firstName: newFirstName,
this._players.lastName: newLastName,
this._players.age: newAge
}
this._players.push(player);
}
};
let player = {
this._players.firstName: newFirstName,
this._players.lastName: newLastName,
this._players.age: newAge
}
Using this
here would refer to player
, not team
(because player
is the innermost object);
and player does not have a ._players
so there’s an error.
You only have to create a new player object, and then add it to the team._players
array.
_players: [
{ firstName: "Pete", lastName: "Wheeler", age: 54 },
{ fistName: "Thomas", lastName: "Williams", age: 36 }, #firstName is misspelled
{ firstName: "Ryan", lastName: "Reynolds", age: 32 },
],
The player objects seem to have a Firstname
property, a lastName
property, and an age
property.
So when you create a new player object, you’ll need to create an object that has those properties.
addPlayer(newFirstName, newLastName, newAge) {
// create player object
let player = {
firstName: newFirstName,
lastName: newLastName,
age: newAge
}
// add the player object to the ._players array
this._players.push(player);
}
1 Like
Thank you very much for your response! It makes more senses to me now