White Lotus White Lotus - 1 year ago 104
Javascript Question

Prototype using Square Brackets (Vanilla JS solution only)

How can I apply a prototype to constructor function using (square brackets). I don't want to use dot notation because it does not evaluate the variable but rather returns the variable name and I want the prototype to be more dynamic. Below is what I am trying to achieve but I can't get it to work.

var prototyper = function(constructor_name, prototype_name, data)
main[constructor_name][__prototype__][prototype_name] = new Function(data);


Answer Source

You want bracket notation for the variable properties (…[constructor_name] and …[prototype_name]) but dot notation for the constant property ….prototype. You will need to mix them into

function prototyper(constructor_name, method_name, fn) {
    main[constructor_name].prototype[method_name] = fn;

(jsfiddle demo)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download