0

I'm using simple class-mechanism:

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;
}

Using:

let UserModel = Model.define('UserModel', { /* UserModel proto */ });
let john = new UserModel( /* blabla */ );

All right. But when I loging objects in Web Developer Tools I see "> NewClass {…}". Because variable in method "define" called "NewClass". I wanna see different class names in the console. How can I do that?

I've tried

  1. eval by new Function(name, function ${name}{ /* code */)
  2. protoObj.constructor = {name: name}
  3. let o = {}; o[name] = function(){...}; let NewClass = o[name]
  4. Object.defineProperty(NewClass, 'name', { get...
  5. NewClass.name = name; // throw error

P.S. sorry for my english

faiwer
  • 1,808
  • 1
  • 15
  • 17
  • If I'm getting your question right, this might be the answer http://stackoverflow.com/questions/9803947/create-object-from-string – halfzebra Sep 28 '15 at 08:55
  • No. I'm say about this: http://ftp.faiwer.ru/img_28_09_14:58:48_8ef23be22f4.png . I wanna see "> A" instead "NewClass" – faiwer Sep 28 '15 at 08:59
  • 1
    Not that I'm saying you *should* use it, but out of interest, why didn't `eval` work? `var NewClass = eval("(function " + name + "() {})");` should work fine. [Example](http://jsfiddle.net/n9jjvsnw/). Additionally, you're passing your parameters wrong in your example – CodingIntrigue Sep 28 '15 at 09:00
  • @RGraham, hm... Good. I've tried only `new Function` variant. And it not worked. Variant with `window.eval` working. – faiwer Sep 28 '15 at 09:06
  • @faiwer What's `this.construct`? Do you mean [Reflect.construct](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/construct)? – CodingIntrigue Sep 28 '15 at 09:09
  • @RGraham, not. It's equal __construct in php. – faiwer Sep 28 '15 at 09:16
  • @halfzebra try it without string literals. Use variable instead 'Foo' :) – faiwer Sep 28 '15 at 09:20
  • @faiwer true, I haven't checked that. – halfzebra Sep 28 '15 at 09:24

1 Answers1

1

You can create a new object using the Function constructor and give it a name:

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

JsFiddle Example

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Good. Your right, I've used wrong parameters before. May be exists variant without eval? For production? – faiwer Sep 28 '15 at 09:09