2

I'm trying to round out my Javascript knowledge. This seems like such a simple thing, yet it's puzzling me.

I have a need to store a method name as a variable. Reducing my test case to the smallest possible size, results in the following:

var someobj = { 
  someMethod: function() {
      console.log('woo');
  }, 
  somevariable: this.someMethod
}

There are no callbacks, everything's nice and simple.

console.log(someobj.someMethod);

Returns:

[Function]

Great. But:

console.log(someobj.somevariable)

Returns:

undefined

I was expecting it to return '[Function]'. Why is this?

Thanks.

1 Answer 1

1

When declaring objects in JSON - format, there is no this keyword. (well, there is, but i refers to the this of the outer context, for example window in a global context) You cannot access the current object in such a declaration. You will thus need to set that variable afterwards, something like this:

var someobj = { 
  someMethod: function() {
      console.log('woo');
  } 
}
someobj.somevariable = someobj.someMethod;
Sign up to request clarification or add additional context in comments.

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.