Object Syntax
const myCat = { firstName: 'Pedro', 'Middle Name': 'P.', // invalid identifier lastName: 'Hofer', age: 4, color: 'black', purrPurr: function (purr) { console.log(purr); }, favoriteFood: ['Animonda', 'ZooRoyal', 'Whiskas'],}Zugriff auf Properties und Values
Section titled “Zugriff auf Properties und Values”myCat.firstName; // Pedro// only bracket notation works with invalid identifiers:myCat['Middle Name']; // P.myCat.lastName; // HofermyCat.age; // 4myCat.color; // black// this function is the value of the property purrPurr// since it is contained in an object, we call it methodmyCat.purrPurr('Pedro says: Meooooow!!!');myCat['purrPurr']('Mrrrrow!!');myCat.favoriteFood[2];
// get the value (?)const age = myCat.age;const ageBracketNotation = myCat['age']; // mind the '' !!!
// get the value of a property through a variable:// (why do we want to do this?)const foodToBuy = 'favoriteFood';const pedrosFood = myCat[foodToBuy]; // why no '' - bc. it is a constant???console.log("Pedro loves " + pedrosFood + ".");Setting the value of a property
Section titled “Setting the value of a property”// with dot notationmyCat.favoriteCanOpener = 'Axel';// with bracket notationmyCat['secondFavoriteCanOpener'] = 'Birgit';Deleting properties
Section titled “Deleting properties”delete.myObject.property
delete myCat['Middle Name'];Enhanced Object Literals
Section titled “Enhanced Object Literals”1. Property value shorthands
Section titled “1. Property value shorthands”Wenn man Objekte erstellt, kann es passieren, dass man einer Eigenschaft eine Variable zuweist, die zufällig genauso heißt wie die Eigenschaft selbst. Dann kann man den Zuweisungsteil weglassen.
const fullName = 'Zell Liew';const Zell = { fullName: fullName,};// mit Shorthand:const ZellShorthand = { fullName,}2. Method shorthands
Section titled “2. Method shorthands”// Declaring a method with a function expression:const Pedro = { purrMyName: function () { console.log('Mrrrrrow Pedro!'); }}
// Method shorthands allow to omit the [: function] part:const PedroShort = { purrMyName() { console.log('Prrrrredro!'); }};3. Declaring a property name through a variable
Section titled “3. Declaring a property name through a variable”… das versteh ich nicht und das ergibt auch immer undefined …
const property = 'myName';obj[property] = 'Bibs';// Computed object property names lets you create objects with// variables as property keys. To do so, wrap the property with// square brackets (dynamic variables).const property2 = 'pedroName';const cat = { [property2]: 'Pedro Hofer',};// changing the property while creating it:const property3 = 'axelName';const person2 = { [property3]: 'Axel', ['full' + property3]: 'Axel Riese',}
// nix verstehen und ergibt undefinedconst property4 = 'name';const person = { [property]: 'Zell', ['full + property']: 'Zell Liew',}console.log(person.fullname);