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

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

本文介绍了在构造函数中定义原型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();
}

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

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?

谢谢!
Grace

Thanks!Grace

推荐答案

由于种种原因,这是一个非常糟糕的主意。其中一些是:

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


  1. 在构造函数中向原型添加方法将导致每次更新所有实例的prototype方法实例化一个新的狗。

  2. 调用 Dog.prototype.bark()表示这个将是 Dog.prototype 而不是 Dog 的实例,这可能会导致严重问题。

  3. this.bark = function(){Dog.prototype.bark(); } 是一些严重的WTF。因为 this.bark 已经评估了原型方法,因此不需要这样做。并且这样调用它实际上会破坏自然这个值,如#2中所述。

  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.

这应该是:

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

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

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

或者,根本没有原型:

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

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

  this.makeSound();
};

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

I would not trust this snippet of yours at all.

这篇关于在构造函数中定义原型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:55