Reputation: 67
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?
Upvotes: 3
Views: 83
Reputation: 4506
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.)
Upvotes: 2
Reputation: 858
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();
Upvotes: 2