简体   繁体   中英

javascript - how to refer object itself?

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?

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 (ie 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.)

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM