0

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);
   }
 };
2
  • You could use a factory but that wouldn't be so different from the first code. what's your problem with it ? Commented Mar 27, 2013 at 17:32
  • I don't understand what benefit the declaration has that the expression doesn't. Commented Mar 27, 2013 at 17:35

3 Answers 3

2

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 };
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.