3
var myObj= function(){
 console.log(self.myNum) //<- need to fix here
}
myObj.myNum=3;
myObj();

I want to use myObj.myNum inside of myObj but not using myObj..

console.log(myObj.myNum) // <-so not this way

also,

console.log(this.myNum) // <-this is not what I want.

this doesn't refer object itself, it refers what calls the function..

Is it even possible?

asked Aug 4, 2015 at 18:56

2 Answers 2

2

You can give a function an extra name that it can use internally:

var myObj = function myOwnObj() {
 console.log(myOwnObj.myNum)
}
myObj.myNum = 47;
myObj();
answered Aug 4, 2015 at 19:44
Sign up to request clarification or add additional context in comments.

Comments

2

This is a slightly unusual use case. If you explained your problem in more detail, maybe ultimately we'd find a better aproach.

I don't see how the other suggested answer (was at +2, now deleted) would work. I can think of one convoluted way of doing this: creating a bound function.

Sadly, the naive way of doing that wouldn't work here, for example this code:

var myObj = function(){
 console.log(this.myNum);
}.bind(myObj); //this will not work

will have the global object as this, because at the time of the bind call, myObj is still undefined.

However, you can create an additional function, which is a bound version of your original one, which will interpret this as the original function (i.e. itself), like this:

var myObj = function(){
 console.log(this.myNum);
};
var myBoundObj = myObj.bind(myObj);
myObj.myNum=3;
myBoundObj(); //outputs 3

Here calling myBoundObj() will output 3 as wanted, and it does not refer to itself by its name. (But due to the slight twist, this might not be applicable in your case. The issue of caller context you mention in your edit is not present here once you create the binding.)

answered Aug 4, 2015 at 19:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.