是否可以在JavaScript中在运行时设置函数名称?
var ctor = function() {}; // Anonymous function because I don't know the name ahead of runtime.
ctor.name = 'foo'; // Pseudocode - this is effectively what I want to do
我希望以上内容等同于:
var ctor = function foo() {};
编辑
这是一个用例示例:
function mix(fn1, fn2, name) {
var ctor = function() {};
ctor.name = name; // Vain attempt to set the name of the function.
ctor.prototype = Object.create(fn1.prototype);
Object.keys(fn2.prototype).map(function(k) {
ctor.prototype[k] = fn2.prototype[k];
});
// Return a constructor function with the prototype configured.
return ctor;
}
function Foo() {}
Foo.prototype.foo = function(){};
function Bar(){}
Bar.prototype.bar = function() {};
var Foobar = mix(Foo, Bar, 'Foobar');
console.log(new Foobar()); // ctor {bar: function, foo: function} (in Chrome) - I wanted Foobar { bar: function, foo: function }
name
是仅某些浏览器支持的非标准。
现在,它已在ECMAScript 6中标准化:
该
name
属性的值是一个描述函数的字符串。该名称没有语义意义,但通常是变量或属性名称,用于在ECMAScript代码的定义点引用该函数。此属性具有属性{[[[Writable]]:false,[[Enumerable]]:false,[[Configurable]]:true }。没有与此规范相关联的上下文名称的匿名函数对象不具有
name
自己的属性,而是继承name
%FunctionPrototype%的属性。
因此,您的代码将在不支持的浏览器上工作name
,但是new属性将是可写且可枚举的。在支持该功能的浏览器上,您的代码将无法使用,因为name
它不可写。
因此,更好的等效代码将是
Object.defineProperty(ctor, 'name', {
value: 'foo',
configurable: true
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句