JavaScript: is extending prototype dynamically a bad practice?
Asked Answered
L

1

6

I want to know if extending a Function's prototype dynamically is a bad practice. I'm considering to do this using a static method that receives the property name and the function to add to the prototype.

Is that a bad practice?

function Test() {
    this.condition = false;
}

Test.extend = function(id, task) {
    this.prototype[id] = function() {
        return task.apply(this, arguments);
    };
};
Lavonna answered 11/5, 2016 at 9:9 Comment(5)
Only if you abuse it to the point where keeping track is hard (which, frankly, is usually what happens). Personally, I prefer to not reach that level of meta in my programming.Ashtoreth
It's a bad practice because your code doesn't work :-) It would need to be task instead of this.task, and should be shortened to this.prototype[id] = task;Parallax
I'm not sure but I guess there are some performance issues with .apply.Erect
@Erect performance issues with apply? Since when? Not to mention the fact that this whole thing assumes modifying prototypes dynamically, which has waaay bigger perf implications that using Function.prototype.apply...Shameful
This practice, the way you've presented it, is a bad idea: just adding random methods to prototypes that insta-modify every existing object created by a given constructor. Nor is the .apply necessary. Generally speaking, as a rule of thumb, inheritance is bad. Inheritance that is not visible by glancing at the source code is worse. And prototypal inheritance is still inheritance.Shameful
J
0

I would say it is bad practice in this instance, as you have no control over if an [id] method being added gets overidden from within the class.

var test = new Test();
test.extend("example", function() {
    console.log("First Method");
});

test.extend("example", function() {
    console.log("Second Method");
});

With how your code is, you have no way of knowing when the first method gets overidden and thus randomly breaking your code.

Jiujitsu answered 13/7, 2016 at 15:16 Comment(1)
Well, this can be solved checking the methods added to the prototype before adding a new one. But if you have this check, extending the prototype this way is a bad practice?Lavonna

© 2022 - 2024 — McMap. All rights reserved.