I am attempting to use a function declaration within an object but am so far unable to. I know I can use function expressions within an object but is it possible to use function declarations instead?
This works:
var objContainer = {};
objContainer.callback = function(data) {
objContainer.server_date = data.responseXML.documentElement.getAttribute("answer");
alert("Object should have XML response: " + objContainer.server_date);
};
This doesn't:
var objContainer = {};
function objContainer.callback(data) {
objContainer.server_date = data.responseXML.documentElement.getAttribute("answer");
alert("Object should have XML response: " + objContainer.server_date);
}
I also tried using a function declaration using object literal notation but it also fails:
var objContainer = {
function callback(data) {
var objContainer.server_date = data.responseXML.documentElement.getAttribute("answer");
alert("Object should have XML response: " + objContainer.server_date);
}
};
-
You could use a factory but that wouldn't be so different from the first code. what's your problem with it ?Denys Séguret– Denys Séguret2013年03月27日 17:32:24 +00:00Commented Mar 27, 2013 at 17:32
-
I don't understand what benefit the declaration has that the expression doesn't.Kendall Frey– Kendall Frey2013年03月27日 17:35:43 +00:00Commented Mar 27, 2013 at 17:35
3 Answers 3
I know I can use function expressions within an object but is it possible to use function declarations instead?
No. Only expressions.
The closest you could get would be to have a function declaration in scope, and then assign the function to an object property by name.
function foo () { }
var bar = { func: foo };
Comments
If I'm understanding you correctly, you just want to use the "function funcname() { .. }" syntax instead of "obj.prop = function() { .. }" correct? The only way you'll be able to do that is using something like this:
function objContainer() {
this.callback = callback;
function callback(data) {
alert(data);
}
};
var myObjectContainer = new objContainer();
myObjectContainer.callback('hello world');
When you call a function using "varName = new funcName()" it creates an object.
Comments
For the last one example I think this is what you want:
var objContainer = {
callback : function(data) {
var objContainer.server_date = data.responseXML.documentElement.getAttribute("answer");
alert("Object should have XML response: " + objContainer.server_date);
}
};
// then you could use the object like this:
objContainer.callback();