Javascript get parent / variable name

Say I have

var myObject = { 'myFunction' : function () { // something here that lets me get 'myObject' } } 

I tried various functions found here and things like this.constructor.name , but I always get "Object" as the return value. Is there a way to get the actual variable name in this situation?

change to explain why, maybe people will understand better ... I want to be able to make a function that is constantly called with setInterval. Something like that:

 var myObject = { 'intval' : '', 'timeout' : 500, 'start' : function () { this.objectName = 'myObject'; // <--I want this to be dynamically popped this.intval=window.setInterval("window['"+this.objectName+"'].myFunction()",this.timeout); }, 'stop' : function () { window.clearInterval(this.intval); this.intval=''; }, 'myFunction' : function () { // do something } } 

This works fine if I hardcode 'myObject' to this.objectName, but I don't want it to be hard coded. The problem is that I just did not execute setInterval("window[this.objectName]",100) because this is not in the right context when setInterval`, and I do not want to have a hardcoded object name

+4
source share
4 answers

One way:

 var myObject = { 'myFunction' : function () { for (var name in window) { if (window[name] === this) { alert(name); break; } } } } 

Not very good IMO, a little better if you wrap it in your own namespace.

You can also always

 var myObject = { moniker: "myObject", ... 

In the light of your update, you do not need to resolve the object at all;

 var myObject = { 'intval' : '', 'timeout' : 1500, 'start' : function () { var self = this; this.intval = window.setInterval(function() { self.myFunction() }, this.timeout); }, 'myFunction' : function() { alert(this.intval); } } 
+3
source

No, you cannot do this in JavaScript.

+5
source
 for (var name in this.global) if (this.global[name] == this) return name 

How to get class object name as a string in Javascript?

+1
source

In short, no.

The way you create your objects, myObject is nothing more than a shortcut with a (relatively loose) link to the object literal. In terms of Java or C ++, myObject more like a pointer and then a class name. If you need a stronger relationship between the myObject label and the object that it refers to, you will need to use a constructor or subclass template. See this article on golimojo.com for a pretty solid review.

+1
source

Source: https://habr.com/ru/post/1415422/


All Articles