简体   繁体   English

javascript - 如何引用对象本身?

[英]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 .. 我想在myObj使用myObj.myNum 但不使用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.. this不是指对象本身,它指的是什么调用函数..

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. 我没有看到其他建议的答案(在+2,现在已删除)如何工作。 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. 将具有全局对象为this ,因为在绑定调用的时候,MyObj中仍然是不确定的。

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: 但是,您可以创建一个附加函数,它是原始函数的绑定版本,它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. 这里调用myBoundObj()将根据需要输出3,并且它不会通过其名称引用它自己。 (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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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