如何在JavaScript中设置类工厂中的类名?

时间:2015-09-28 08:39:08

标签: javascript class native-code

我使用简单的类机制:

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 Developer Tools中记录对象时,我看到"> NewClass {...}"。因为方法中的变量"定义"叫" NewClass"。我想在控制台中看到不同的类名。我怎么能这样做?

我已经尝试了

  1. eval by new Function(name,function ${name}{ /* code */
  2. protoObj.constructor = {name:name}
  3. 让o = {}; o [name] = function(){...};让NewClass = o [name]
  4. Object.defineProperty(NewClass,' name',{get ...
  5. NewClass.name = name; //抛出错误
  6. P.S。对不起我的英文

1 个答案:

答案 0 :(得分:1)

您可以使用Function构造函数创建一个新对象,并为其命名:

var NewClass = new Function(
     "return function " + name + "(){ }"
)();

JsFiddle Example