简体   繁体   中英

Can JavaScript refer to itself?

Is it possible for a piece of JavaScript code to refer to itself? That is, can I programmatically build a variable such that its value is the raw text content of the JavaScript file declaring it?

Try,

(function foo() { var f = foo.toString(); return f; })()

where f is a variable as you describe. This also returns itself as string just for good measure.

(function () { return arguments.callee.toString(); })()

Almost the same thing as the selected answer, w/o the variable storage of the string, or the function name. Neither really refers to itself. You can't do something like $(this).closest('script') to refer to the JS file in the DOM.


What you can do is something similar to this :

var w      =  window;
w.stored   =  [];
w.scripts  =  document.getElementsByTagName('script');
w.stored.push(w.scripts[ w.scripts.length - 1 ]);

As stated, this can be done because the DOM loads scripts sequentially. You can refer to all the scripts that did this like w.stored[0] . Using jQuery you could do $(w.stored[0]).text()

JSFiddle Demo

Is it possible for a piece of JavaScript code to refer to itself?

It is possible for a function to refer to itself using arguments.callee (ECMA-262 10.6). I think it's not available in strict mode but that shouldn't be too much of an issue. You can call the function's toString method to get an implementation-dependent representation of the function , which is typically a string equivalent to the source code that created it, but it may not be.

That is, can I programmatically build a variable such that its value is the raw text content of the JavaScript file declaring it?

Not in a general sense, eg you can't do:

var x = 'x';
getVaue(x); // var x = 'x';

if that is what you mean.

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