这些原型声明有什么区别? [英] What is the difference between these prototype declaration?

查看:372
本文介绍了这些原型声明有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法1:

Rectangle.prototype.getArea = function() {
     return this.length * this.width;
};

方法2:

Rectangle.prototype = {
     getArea: function() {
          return this.length * this.width;
     }
};

上述每种方法的区别和优势是什么?

What are the differences and advantages of each of the methods above?

推荐答案

在第一种情况下,您新属性添加到现有对象,在第二种情况下,您覆盖 Rectangle.prototype 带有新值(对象)。

In the first case you are adding a new property to an existing object, in the second case you are overwriting Rectangle.prototype with a new value (object).

覆盖原型会产生以下后果:

Overwriting the prototype has the following consequences:


  • Rectangle.prototype.constructor 未指向矩形了。当您使用对象文字时,它将指向对象。这可以通过分配

  • Rectangle.prototype.constructor does not point to Rectangle anymore. When you use an object literal, it will point to Object instead. This can easily by solved by assigning

Rectangle.prototype.constructor = Rectangle;


  • 您可能会丢失原型上的所有现有属性(除非您再次添加它们,例如构造函数)。

    的现有实例Rectangle 不会受到更改的影响。他们仍将引用旧原型而不继承新方法/属性。

    Existing instances of Rectangle will not be affected by the change. They will still reference the old prototype and don't inherit the new methods/properties.

    instanceof 现有实例(即 rect instanceof Rectangle )的测试将失败,因为 instanceof 比较原型,如前所述,现有实例保留对旧原型的引用。

    instanceof tests on existing instances (i.e. rect instanceof Rectangle) will fail, since instanceof compares prototypes and as mentioned in the previous point, existing instances keep their reference to the old prototype.

    如果你在创建任何实例之前设置原型,那么你不必关心最后三点。

    If you set up the prototype before you create any instances then you don't have to concern yourself with the last three points.


    上述每种方法的区别和优势是什么?

    What are the differences and advantages of each of the methods above?

    使用对象文字覆盖原型的唯一好处是简洁的语法。 IMO它不会超过缺点。

    The only advantage of overwriting the prototype using an object literal is the more concise syntax. IMO it does not outweigh the disadvantages though.

    你可以使用一个对象文字,而不是通过合并这两个对象来覆盖原型:如何动态合并两个JavaScript对象的属性?

    You can use an object literal without overwriting the prototype by merging the two objects: How can I merge properties of two JavaScript objects dynamically?.

    这篇关于这些原型声明有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆