Reputation: 800
So I created a variable car and then assigned it to a function and added the arguments model, year. Then created an object within the function with reference to the arguments.
Then Created the "closure" inner function yourCar() and returned the outer functions object "Properties" within it. followed by returning the inner function yourCar() within the outer function to be available on a global scope.
So to my understanding I thought the inner function has access to all of the variables and functions to the outer function. Thus I called yourCar(model, year); to get the object variables.
But keep getting the error message : "yourCar is not defined"... I am using scratchpad on mozilla fox to test and debug. Can anyone help with this, so I can understand it a bit better!
var car = function(model, year){
var Properties = {
model: nissan,
year: 2004
}
function yourCar() {
return Properties;
}
return yourCar();
}
yourCar(model, year);
Upvotes: 0
Views: 67
Reputation: 11763
Like both said, you're trying to reach a private method on the wrong object.
here's a JSBIN demo: http://jsbin.com/acohoYUP/2/edit?js,console
Mainly holding:
var car = function(model, year){
var Properties = {
model: "nissan",
year: 2004
};
function yourCar() {
return Properties;
}
return yourCar();
};
var updatedCar = function(model, year){
var Properties = {
model: model,
year: year
};
function yourCar() {
return Properties;
}
return yourCar();
};
var badCar = car("lemon", 1999);
var goodCar = updatedCar("ferrari", 2014);
You can see that the stats on badCar
will be nissan
and 2004
, instead of the parameters passed (using badCar.year
for example).
On the goodCar
, like pswg suggested, they are correct.
Upvotes: 1
Reputation: 149000
You've defined yourCar
as a function only within the scope of car
(or more accurately, the anonymous function bound to car
). So outside of car
, yourCar
doesn't mean anything; it's undefined.
It looks like you were trying to do something like this:
var car = function(model, year){
var Properties = {
model: model,
year: year
};
function yourCar() {
return Properties;
}
return yourCar();
}
var result = car('nissan', 2004);
Upvotes: 1
Reputation: 239443
yourCar
is defined inside car
. Only the functions and variables insider car
can access yourCar
. It is kind of private to the car
function. So, you cannot access it outside. You should be actually calling car
, like this
car (model, year);
Upvotes: 2