在构造函数中定义原型方法

Gra*_*hao 9 javascript prototype-programming

今天,我看到了我一生中从未见过的JavaScript模式.我无法说出使用这种模式的目的.这对我来说似乎不对,但我想保守一点.这可能是我以前从未见过的一些很棒的模式.

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

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

    this.bark();
}
Run Code Online (Sandbox Code Playgroud)

首先,我不是没有理由在构造函数中创建方法(作为特权成员)的粉丝.每次创建实例时都会导致创建函数.其次,在这段代码片段中,它还调用原型名称"Dog",而不是"this".这让我非常困惑.

谁知道它有什么好处?

谢谢!恩典

Ale*_*yne 13

出于很多原因,这是一个非常糟糕的主意.其中一些是:

  1. 在构造函数中向原型添加方法将导致每次实例化一个新Dog时替换所有实例的prototype方法.
  2. 调用Dog.prototype.bark()意味着this将是Dog.prototype您的实例,而不是您的实例Dog,这可能会导致严重的问题.
  3. this.bark = function () { Dog.prototype.bark(); }是一些严肃的WTF.因为this.bark已经评估了原型方法使得这不必要了.并且这样称它实际上破坏了自然this价值,正如#2中提到的那样.

这应该是:

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

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

Dog.prototype.makeSound = function() {
  this.bark();
};
Run Code Online (Sandbox Code Playgroud)

或者,根本没有原型:

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

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

  this.makeSound();
};
Run Code Online (Sandbox Code Playgroud)

我根本不相信你的这个片段.