1

I'm looking into creating dynamic objects in Javascript. The way I'd like this to work is similar to new self(); in PHP. Solutions like down here unfortunately didn't solve the problem.

function factory(class_) {
    return new class_();
}

The code sample given is causing me trouble.

import Model from './Model';
var className = 'course';

    class Course extends Model {


        save(success) {
            API.post(className, this.data(), success, function() {
                // notify the user if something went wrong.
            });
        }

        static all(success, failure) {
            API.get(className, (objects) => {
                let all = [];
                for(let object in objects) {
                    let newObject = new Course(objects[object]);
                    all.push(newObject);
                }
                success(all);
            }, failure);
        }

    }

    export default Course;

So to be clear, I'd like Course in let newObject = new Course(objects[object]); to be dynamically assigned.

Instead of typing new Course(); I would like to do something like:

var className = 'Course';

let newObject = new className(objects[object]);

Naturally, this doesn't work. But how could I get it to work?

Thanks in advance!

Eric Landheer
  • 2,033
  • 1
  • 11
  • 25
  • What part of that exactly should be dynamic? – deceze Aug 03 '17 at 10:28
  • I don't understand your question :) – Vad Aug 03 '17 at 10:30
  • I'm sorry if I'm being unclear. Instead of typing new Course(); I would like to do something like: var className = 'Course'; let newObject = new className(objects[object]); I hope you catch my drift. – Eric Landheer Aug 03 '17 at 10:32
  • OK, so the linked duplicate should answer your question then. You don't look up classes by name like in PHP, you would just get a handle on the "actual class" (constructor function) using "variable variables". – deceze Aug 03 '17 at 10:35
  • No, that would not solve the problem, it would merely move the problem. Unfortunately the linked duplicate is not an answer, as it doesn't involve creating objects. If you see the var className on top of the file, I'd like that to create new objects using that particular variable. – Eric Landheer Aug 03 '17 at 10:39
  • 1
    Well, you can't create an object from a string. You *have* to do something like: `let objs = { course: Course }; new objs[className]();` – "variable variables" in Javascript. – What you're trying to do really doesn't translate well from PHP to Javascript at all. – deceze Aug 03 '17 at 10:40
  • Thanks a bunch, that solved the problem! – Eric Landheer Aug 03 '17 at 10:46

0 Answers0