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

8
  • If I'm getting your question right, this might be the answer stackoverflow.com/questions/9803947/create-object-from-string Commented Sep 28, 2015 at 8:55
  • No. I'm say about this: ftp.faiwer.ru/img_28_09_14:58:48_8ef23be22f4.png . I wanna see "> A" instead "NewClass" Commented Sep 28, 2015 at 8: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. Additionally, you're passing your parameters wrong in your example Commented Sep 28, 2015 at 9:00
  • @RGraham, hm... Good. I've tried only new Function variant. And it not worked. Variant with window.eval working. Commented Sep 28, 2015 at 9:06
  • @faiwer What's this.construct? Do you mean Reflect.construct? Commented Sep 28, 2015 at 9:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Good. Your right, I've used wrong parameters before. May be exists variant without eval? For production?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.