Defining prototypes inside a constructor

Today I saw a JavaScript template that I had never seen in my entire life. I can not say the purpose of using this template. It seems wrong to me, but I want to be a little conservative. This may be some amazing pattern that I have never seen before.

function Dog() { Dog.prototype.bark = function () { alert('woof!'); } this.bark = function () { Dog.prototype.bark(); } this.bark(); } 

First, I'm not a fan of creating methods (as privileged members) inside the constructor for no reason. This will cause functions to be created each time an instance is created. Secondly, in this code snippet, it also calls the prototype name β€œDog” instead of β€œthis”. It bothers me.

Does anyone know what's good about it?

Thanks! Grace

+8
javascript prototype-programming
source share
2 answers

This is a very bad idea, for many reasons. Some of them:

  • Adding methods to the prototype in the constructor will replace the prototype method for all instances, each time you create a new dog.
  • Calling Dog.prototype.bark() means that this will be Dog.prototype , not your instance of Dog , which can cause serious problems.
  • this.bark = function () { Dog.prototype.bark(); } this.bark = function () { Dog.prototype.bark(); } is a serious WTF. Because this.bark will already evaluate the prototype method, making this unnecessary. And, calling it that, actually destroys the natural meaning of this , as stated in No. 2.

Here's what it should be:

 function Dog() { this.makeSound(); }; Dog.prototype.bark = function() { alert('woof'); }; Dog.prototype.makeSound = function() { this.bark(); }; 

Or, alternatively, without a prototype at all:

 function Dog() { this.bark = function() { alert('woof'); }; this.makeSound = function() { this.bark(); }; this.makeSound(); }; 

I do not trust this fragment at all.

+12
source share

Sorry for the VERY late answer, but if you really want to add prototypes inside the constructor AND don't recreate it every time a new instance is created, you can do this:

 function Dog() { if (!Dog.prototype.bark) { Dog.prototype = function() { console.log('woof'); } } this.bark(); } 

I still probably will not use this method, but I have several instances where this method was an option when working with third-party frameworks (perverted view).

+2
source share

All Articles