gpt4 book ai didi

javascript - 更改匿名函数的名称?

转载 作者:搜寻专家 更新时间:2023-11-01 04:42:23 24 4
gpt4 key购买 nike

函数对象有一个非标准属性,叫做名称。有谁知道改变它的方法?或者任何其他方式来更改匿名函数的名称?如果 JavaScript 可以创建动态命名的变量就好了,但它似乎只能创建公共(public)对象属性名称。
我想做什么?
我正在努力实现这样的目标。

// o - literal object, or json
// c - string
function givemeConstructor(o, c, a}){
var a = a || 'Object';
// check other variables
var cons;

if(a === 'Object'){
cons = function(){};
for(p in o) cons.prototype[p] = o[p];
cons.name = c;
}
else{
// a way to create a constructor that inherits from a
// adds object as new prototype
}

return cons;
}

var cons = givemeConstructor({x:1,y:1, toString:function(){return '['+ x + ','+ y+'']'}, 'Point'})


最终得到一个可自省(introspection)的对象。

最佳答案

我不清楚你在这里玩的模式,但混淆似乎是将 name 属性添加到构造函数不允许你引用它我的那个名称。它的“名称”是您分配给它的任何变量。

根据你到目前为止所做的,我认为这会给你你想要的 -

function givemeConstructor ( proto ){
var tmp = function(){};
tmp.prototype = proto;
return tmp;
}

var Point = givemeConstructor( {x:1 ,y:1, toString:function(){return '['+ this.x + ','+ this.y +']' } } );
var p = new Point;

注意事项:

  1. 您的函数需要使用this.xthis.y 来访问原型(prototype)中的变量
  2. 如果你这样做,你的构造函数不能接受 xy 参数
  3. 您可以检查 Point.prototype 或实例化并检查 p
  4. Function.name 设置为 Point 是毫无意义的,不会改变构造函数的引用方式。

关于javascript - 更改匿名函数的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543968/

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