Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Defining prototype methods inside the constructor

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a very bad idea, for a great number of reasons. A few of which are:

  1. Adding methods to the prototype in the constructor will cause the prototype method to be replaced for all instances, everytime you instantiate a new Dog.
  2. Calling Dog.prototype.bark() means that this will be Dog.prototype and not your instance of Dog, which can cause serious issues.
  3. this.bark = function () { Dog.prototype.bark(); } is some serious WTF. Because this.bark will already evaluate to the prototype method making this unnecessary. And calling it like this actually destroys the natural this value, as mentioned in #2.

Here is what is should be:

function Dog() {
  this.makeSound();
};

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

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

Or alternatively, without the prototype at all:

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

  this.makeSound = function() {
    this.bark();
  };

  this.makeSound();
};

I would not trust this snippet of yours at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...