【发布时间】:2015-09-28 08:39:08
【问题描述】:
我正在使用简单的类机制:
function define(SuperClass, name, proto)
{
let ProtoFn = function(){};
ProtoFn.prototype = SuperClass.prototype;
let protoObj = new ProtoFn;
var NewClass = function()
{
this.construct.apply(this, arguments);
};
_.extend(protoObj, proto,
{
constructor: NewClass,
_class: NewClass,
_parent: SuperClass
});
NewClass.prototype = protoObj;
NewClass.className = name;
NewClass.define = define.bind(null, NewClass);
return NewClass;
}
使用:
let UserModel = Model.define('UserModel', { /* UserModel proto */ });
let john = new UserModel( /* blabla */ );
好的。但是,当我在 Web 开发人员工具中记录对象时,我看到 "> NewClass {…}"。因为方法“define”中的变量称为“NewClass”。我想在控制台中看到不同的类名。我该怎么做?
我试过了
- 通过新函数评估(名称,
function ${name}{ /* code */) - protoObj.constructor = {name: name}
- 让 o = {}; o[名称] = 函数(){...};让 NewClass = o[名称]
- Object.defineProperty(NewClass, 'name', { get...
- NewClass.name = 名称; // 抛出错误
附:对不起我的英语
【问题讨论】:
-
如果我的问题没问题,这可能就是答案stackoverflow.com/questions/9803947/create-object-from-string
-
没有。我要说的是:ftp.faiwer.ru/img_28_09_14:58:48_8ef23be22f4.png。我想看到“> A”而不是“NewClass”
-
不是我说你应该使用它,但出于兴趣,为什么
eval不起作用?var NewClass = eval("(function " + name + "() {})");应该可以正常工作。 Example。此外,您在示例中传递的参数错误 -
@RGraham,嗯...好。我只尝试过
new Function变体。它没有奏效。window.eval工作的变体。 -
@faiwer
this.construct是什么?你的意思是Reflect.construct?
标签: javascript class native-code