I am getting a page() is not defined
error message from Firebug with the following Javascript. Why?
( function() {
var page = function() {
var min_central_width = 10;
function minimumCentralWidth(val) {
min_central_width = val;
}
}
$(document).ready(function() {
page().minimumCentralWidth(400);
});
})();
I am still new to Javascript. How can I avoid this?
I am getting a page() is not defined
error message from Firebug with the following Javascript. Why?
( function() {
var page = function() {
var min_central_width = 10;
function minimumCentralWidth(val) {
min_central_width = val;
}
}
$(document).ready(function() {
page().minimumCentralWidth(400);
});
})();
I am still new to Javascript. How can I avoid this?
Share Improve this question edited Dec 2, 2011 at 16:20 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Dec 2, 2011 at 16:11 Jérôme VerstryngeJérôme Verstrynge 59.7k96 gold badges295 silver badges466 bronze badges 02 Answers
Reset to default 4The problem is that page
isn't returning a value, so page()
is undefined
. You would have to write something like this:
( function() {
var page = function() {
// create an object to return:
var ret = {};
// set its properties:
ret.min_central_width = 10;
ret.minimumCentralWidth =
function (val) {
this.min_central_width = val;
};
// return it:
return ret;
};
$(document).ready(function() {
page().minimumCentralWidth(400);
});
})();
. . . but the above doesn't really do anything. It creates a new object, and sets the object's min_central_width
to 400
. . . but it doesn't use the object for anything, so the above doesn't have any meaningful effect. (Is this just because you removed code that wasn't relevant to the question? If so, then never mind. :-)
Even though there's some good answers here, I'd like to add a few more to provide some possible options depending on what you're doing.
If you truly want to make minimumCentralWidth a property of a Page class, you can do this:
( function() {
var page = function() {
var min_central_width = 10;
this.minimumCentralWidth = function (val) {
min_central_width = val;
alert('set to ' + val);
}
}
$(document).ready(function() {
var p = new page(); //new up your object
p.minimumCentralWidth(400);
});
})();
If you're trying to emulate a static utility class, you can do something like this:
( function() {
var page = new function() { //single instance of your page class
var min_central_width = 10;
this.minimumCentralWidth = function (val) {
min_central_width = val;
alert('set to ' + val);
}
}
$(document).ready(function() {
page.minimumCentralWidth(400);
});
})();
Let me know if you have any specific questions on how these examples work, and I'll try to add in some more details!