Today, I saw a JavaScript pattern I have never seen in my whole life. I cannot tell the purpose of using this pattern. It seems wrong to me, but I want to be a little conservative. It might be some awesome pattern I never saw before.
function Dog() {
Dog.prototype.bark = function () {
alert('woof!');
}
this.bark = function () {
Dog.prototype.bark();
}
this.bark();
}
First, I’m not a fan for making methods (as privileged members) inside the constructor for no reason. It would cause creating functions every time when an instance is created. Second, in this code snippet, it also calls the prototype name “Dog”, instead of “this”. This makes me super confused.
Anyone knows what good about it?
Thanks!
Grace
This is a very bad idea, for a great number of reasons. A few of which are:
Dog.prototype.bark()means thatthiswill beDog.prototypeand not your instance ofDog, which can cause serious issues.this.bark = function () { Dog.prototype.bark(); }is some serious WTF. Becausethis.barkwill already evaluate to the prototype method making this unnecessary. And calling it like this actually destroys the naturalthisvalue, as mentioned in #2.Here is what is should be:
Or alternatively, without the prototype at all:
I would not trust this snippet of yours at all.