Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Cody Smith
3,818 PointsCan someone more experienced help with this Object related question for passing object literals to object constructor.
<!DOCTYPE html>
<html>
<body>
<script>
/**
QUESTION:
Can someone more experienced help with this Object related question for passing object literals to object constructor as an argument, then not being able to use square bracket notation. Dot notation works just fine, see last few lines of code with the console.log() code I was playing around with. So that is great, but wondering why square bracket notation does not work in this scenario on the reference variable codysCar which is my new object.
**/
// object literal used to store my parameters var param = {
color: "red",
passengers: 5,
make: "chevy",
year: 1987
};
// constructor ojbect function function Car(passedP) {
this.color = passedP.color;
this.passengers = passedP.passengers;
this.make = passedP.make;
// not required return this;
}
// constructor object var codysCar = new Car(param);
// test code trying to see why square bracket notation doesn't work when passing a object literal to object constructor as a argument, then calling the new construcotr object with square bracket notation. console.log(codysCar.make); console.log(codysCar.color); //console.log(codysCar["year"]); console.log(codysCar.year); console.log(codysCar["year"]);
</script> </body> </html>
2 Answers
Steven Parker
243,318 PointsIt's not the format, but the field you're trying to return. The constructor function doesn't store a "year". But if you used a field it does store with bracket notation, it will work:
console.log(codysCar["color"]); // shows the same as codysCar.color
Cody Smith
3,818 PointsI get you what your saying I think, was thinking I added it manually as a statement after I originally declared the objects. Think your saying I didn't even define the propertyName to begin with. So I would need to do codysCar.year = 1985; to first set the new property if adding it later in the life of the program, or set it originally when declaring the object. Then the square bracket notation for calling property names will still work by saying codysCar['year']; which should return 1985 just like dot nation codysCar.year; . I coded for a few hours yesterday morning, guess that got passed me. Thank you.