Javascript - how to pass an object myself?

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

myObj();

      

I want to use myObj.myNum

internally myObj

, but not using myObj

..

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

      

and

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

      

this

does not refer to the object itself, it refers to what is calling the function.

Is it possible?

+3


source to share


2 answers


You can give the function an alternate name that it can use internally:



var myObj = function myOwnObj() {
    console.log(myOwnObj.myNum)
}
myObj.myNum = 47;
myObj();

      

+2


source


This is a slightly unusual use case. If you explain your problem in more detail, we may eventually find a better approach.

I don't see how the other suggested answer (would have been at +2, now deleted) would work. I can imagine one tricky way to do this: create a bound function.

Unfortunately, a naive way of doing it won't work here, for example this code:

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

      



will have a global object like this

because at the time of the bind call myObj is still undefined.

However, you can create an additional function that is a related version of your original one that interprets this

as the original function (i.e. itself), for example:

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

myBoundObj(); //outputs 3

      

Here the call myBoundObj()

will output 3 as needed and it does not refer to itself by its name. (But due to the slight twist, this might not apply in your case. The caller context issue you mention in your edit is not present here when you create the binding.)

+2


source







All Articles