gpt4 book ai didi

javascript - 在运行时在 JavaScript 中设置函数的名称

转载 作者:行者123 更新时间:2023-11-29 10:41:11 25 4
gpt4 key购买 nike

是否可以在运行时在 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 中标准化:

19.2.4.2 name

The value of the name property is an String that is descriptive of the function. The name has no semantic significance but is typically a variable or property name that is used to refer to the function at its point of definition in ECMAScript code. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

Anonymous functions objects that do not have a contextual name associated with them by this specification do not have a name own property but inherit the name property of %FunctionPrototype%.

因此,您的代码将在不支持 name 的浏览器上运行,但新属性将是可写和可枚举的。在支持它的浏览器上,您的代码将无法运行,因为 name 不可写。

因此,更好的等效代码是

Object.defineProperty(ctor, 'name', {
value: 'foo',
configurable: true
});

关于javascript - 在运行时在 JavaScript 中设置函数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28861941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com