【问题标题】:Javascript: Why to use define prototype method for inheritance if inheritance can be achieved without it? [duplicate]Javascript:如果没有它可以实现继承,为什么要使用定义原型方法进行继承? [复制]
【发布时间】:2016-10-25 10:49:42
【问题描述】:

我参考了this 问题/答案来了解原型继承。

我知道要扩展一个方法,我们需要在基类中定义Person.prototype.getName。这样在子类中就可以称为myCustomer.sayMyName();

答案中的代码可以总结如下:

  function Customer(name) {
        this.firstName = name;
    };
    function User() {
     
    }

    Customer.prototype.hi = function() {
        console.log('Test method of parent');
    }	

    User.prototype = new Customer('shaadi');
    var myUser = new User();
    myUser.hi();

但问题是如果我可以用以下语法调用相同的,我为什么要使用原型?

我的代码:

function Customer(name) {
        this.firstName = name;
        this.hi= function() {
            console.log('Test method of parent');
        }	
    };
    function User() {
     
    }
    User.prototype = new Customer('shaadi');
    var myUser = new User();
    myUser.hi();

我可以在不定义Customer.prototype.hi的情况下使用parent的方法,那么为什么/何时应该使用Customer.prototype.hi

如果两种解决方案都可以让我访问父母的方法,我为什么要选择前者?

【问题讨论】:

    标签: javascript object inheritance prototype prototypal-inheritance


    【解决方案1】:

    这是为了内存使用..

    在您的第二个示例中,对象的每个实例都将拥有它自己的函数 hi()..

    通过将函数 hi() 放在原型上,该函数只会有一个实例。如果创建了数千个这样的对象,则会大量节省内存使用量。

    【讨论】:

      【解决方案2】:

      前者的内存使用要好得多,因为该方法只定义一次。

      第二个例子,函数在每个实例上声明。

      此外,原型方法可以被修改/覆盖,并且这些变化继承到每个使用中的实例中。

      例如

      function Customer(name) {
          this.firstName = name;
      };
      function User() {
      
      }
      
      Customer.prototype.hi = function() {
          console.log('Test method of parent');
      }   
      
      User.prototype = new Customer('shaadi');
      var myUser = new User();
      Customer.prototype.hi = function() {
          console.log('New Test method of parent');
      } 
      myUser.hi();
      

      上面的原型函数在调用自定义类和用户类后发生了变化,但是它的变化仍然会影响所有实例。

      【讨论】:

        【解决方案3】:

        您的两个示例在功能上非常接近。最好用一个类比来解释这种差异:

        假设您有一个目录树A 及其文件,您希望在其他目录BC 中显示。您可以采取两种方式:

        1. A 及其所有内容复制到BC 的某个位置,从而在A 中拥有3 个独立的数据副本。

        2. BC 中放置指向A 的链接。 A 中的数据只存在一次,但也可以从 BC 访问和查看。

        在第二种情况下,这也意味着更改A中的一个文件将显示BC中的更改,就像更改原型属性会影响类的所有实例一样。

        【讨论】:

          猜你喜欢
          • 2011-01-06
          • 1970-01-01
          • 2015-10-29
          • 2012-07-14
          • 2015-03-19
          • 1970-01-01
          • 2018-02-14
          • 2013-10-14
          • 2011-03-02
          相关资源
          最近更新 更多