0
var model = {

   test:function(){console.log("hello")},

   show: test() //ReferenceError: test is not defined
}

I want to have a key inside model object to hold a function. Not sure why it gets undefined error.

3
  • 2
    You can't reference the contents of an object literal from inside while it's "under construction". You have to use a separate statement. Commented Feb 19, 2015 at 17:53
  • You mean I can only call this function outside of object? Commented Feb 19, 2015 at 17:55
  • Yes. There's just no way to do it in JavaScript all inside a single object literal. Commented Feb 19, 2015 at 17:59

2 Answers 2

1

Hope it helps .

var model = {

  test: function() {
    alert("hello")
  },
  show: function() {
    return this.test();
  }
}

model.test();
model.show();

use key show as a function, return test from it.

Sign up to request clarification or add additional context in comments.

Comments

0

I know this is a duplicate but I can't find a good one. You have to do something like this:

var model = {

   test:function(){console.log("hello")},

};
model.show = model.test();

If you want to make it less ... primitive, I guess, you can write a constructor function to encapsulate that stuff, or perhaps a "factory"-like function to do so.

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.