Reputation: 9169
I'm new to Javascript, and I'm learning how to use OOP principals. I'm stuck on assigning object properties and then accessing them later. Let's say I have this function that assigns properties to an object "Car".
function assignProps()
{
Car.size="small";
Car.cost="expensive";
}
The object Car with empty properties because they are assigned from the function.
var Car =
{
size:"",
cost:"",
returnSize: function()
{
return this.size;
},
returnCost: function()
{
return this.cost;
},
}
Now, I want to call the function that assigned the value, and then access Car's properties. I tried doing this, but it obviously failed:
function accessProps()
{
assignProps();
console.log(Car.returnSize());
console.log(Car.returnCost());
}
Any help would be appreciated. I have a feeling that this might have to do with constructors or prototypes, but since there are so many ways to create custom objects in Javascript, the documentations are very confusing.
EDIT: By "fail" I mean that it outputs the blank instead of the newly assigned value EDIT: I tried doing it this way as well, and it yielded the same result.
Upvotes: 0
Views: 52
Reputation:
Line 18, column 14: Extra comma.
Line 20, column 2: Missing semicolon.
Try to get a developing tool with JSLint/JSHint built-in (e.g. Notepad++ with add-on), it might help you with debugging problems like this.
Upvotes: 0
Reputation: 41133
You have a syntax error on your car object initialization, should be
var Car = { size: "", cost: "" };
Upvotes: 0
Reputation: 5676
You have some errors in your code:
var Car = {
size:"",
cost:""
}
And if you look at this fiddle: http://jsfiddle.net/JskBy/ It works as expected.
Full code:
function assignProps() {
Car.size="small";
Car.cost="expensive";
}
var Car ={
size:"",
cost:""
}
function accessProps(){
assignProps();
console.log(Car.size);
}
assignProps();
accessProps();
Upvotes: 1