I have a code like the one bellow and want to detect the instance name of my exScript.
In this case it would be exScript123.
eecore = {
something: 1,
// ...
someelse: function() { /* whatever */ };
};
var exScript = (function (undefined) {
function exScript(inputOptions) {
this.version = "0.0";
}
exScript.prototype.init = function () {
// some code here
};
return exScript;
})();
eecore.exScript123 = new exScript();
eecore.exScript123.init();
I have been experimenting for the last hour with arguments.calle.name and this.parent.name but they do not seem to work in my case. I keep getting undefined.
Slightly modified version of this code:
function objectName(x, context, path) {
function search(x, context, path) {
if(x === context)
return path;
if(typeof context != "object" || seen.indexOf(context) >= 0)
return;
seen.push(context);
for(var p in context) {
var q = search(x, context[p], (path ? path + "." : "") + p);
if(q)
return q;
}
}
var seen = [];
return search(x, context || window, path || "");
}
In your init function
exScript.prototype.init = function () {
console.log(objectName(this, eecore))
};
correctly prints exScript123.
As pointed out in the comments, this is unreliable and a strange idea in general. You might want to clarify why you need that - surely there are better ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With