简体   繁体   English

JavaScript可以引用自身吗?

[英]Can JavaScript refer to itself?

Is it possible for a piece of JavaScript code to refer to itself? 一段JavaScript代码是否可以引用自身? That is, can I programmatically build a variable such that its value is the raw text content of the JavaScript file declaring it? 也就是说,我可以以编程方式构建一个变量,以使其值成为声明它的JavaScript文件的原始文本内容吗?

Try, 尝试,

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

where f is a variable as you describe. f是您所描述的变量。 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. 您无法执行$(this).closest('script')来引用DOM中的JS文件。


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. 如前所述,这是因为DOM会顺序加载脚本。 You can refer to all the scripts that did this like w.stored[0] . 您可以参考执行w.stored[0]所有脚本。 Using jQuery you could do $(w.stored[0]).text() 使用jQuery,您可以执行$(w.stored[0]).text()

JSFiddle Demo JSFiddle演示

Is it possible for a piece of JavaScript code to refer to itself? 一段JavaScript代码是否可以引用自身?

It is possible for a function to refer to itself using arguments.callee (ECMA-262 10.6). 函数可以使用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. 您可以调用函数的toString方法来获取函数的与implementation-dependent representation of the function通常是与创建implementation-dependent representation of the function的源代码等效的字符串,但可能并非如此。

That is, can I programmatically build a variable such that its value is the raw text content of the JavaScript file declaring it? 也就是说,我可以以编程方式构建一个变量,以使其值成为声明它的JavaScript文件的原始文本内容吗?

Not in a general sense, eg you can't do: 从一般意义上讲,例如,您不能:

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

if that is what you mean. 如果那是你的意思。

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

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