简体   繁体   中英

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

prototyper("classify","alert_classification","alert(this.classification)");

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM