有关 Firefox 和 Chrome 控制台中发生的情况,请参见下文:
> var f = function() {}
undefined
> f.name = 'f'
"f"
> f.name
""
> f.id = 1
1
> f.id
1
为什么 f.name = 'f'
是空操作?
最佳答案
可能取决于实现。
在某些实现中,函数对象的 name
属性被用作函数的名称(如果有的话)。在这些情况下,这可能是只读的。
这是一个非标准功能。
例如:
var foo = function bar() {};
alert(foo.name); // will give "bar" in some cases.
在 Firefox 和 Chrome 中,如果我尝试修改它,它不会改变...
var foo = function bar() {};
foo.name = "baz";
alert(foo.name); // still "bar" in Firefox and Chrome
- MDN docs对于
name
属性。
以下是文档中的一些要点...
"Non-standard"
"The name property returns the name of a function, or an empty string for anonymous functions"
"You cannot change the name of a function, this property is read-only"
关于javascript - 为什么 JavaScript 不允许在函数上分配属性 "name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486459/