在JS中定义类(ES5与原型)

时间:2023-02-07 17:02:21

I am looking at some common ways of defining classes (Constructor Pattern in Book by Addy Osmani).

我正在寻找一些定义类的常用方法(Addy Osmani的Book中的Constructor Pattern)。

2 main ways I see:

我看到的两种主要方式:

  • Simple Prototypes:

    简单原型:

    function Person(name) { this.name = name; }
    Person.prototype.getName = function() { return this.name; } 
    
  • ES5 Object.create, Object.defineProperties

    ES5 Object.create,Object.defineProperties

I am wondering, why might I even consider the ES5 way which appears to be alot more complicated? Is there any advantages? Maybe the only main advantage is having read-only properties like some strongly typed language?

我想知道,为什么我甚至可以考虑看起来更复杂的ES5方式呢?有什么好处吗?也许唯一的主要优点是拥有像某些强类型语言这样的只读属性?

1 个解决方案

#1


4  

Object.defineProperties is only needed if you want those properties to have particular attributes, e.g. non-enumerable, read-only, or with getters or setter functions.

只有在您希望这些属性具有特定属性时才需要Object.defineProperties,例如不可枚举,只读或带有getter或setter函数。

There's no need to use it for normal classes and their methods, where the "simple prototype" method you describe is perfectly adequate.

没有必要将它用于普通类及其方法,其中您描述的“简单原型”方法是完全足够的。

#1


4  

Object.defineProperties is only needed if you want those properties to have particular attributes, e.g. non-enumerable, read-only, or with getters or setter functions.

只有在您希望这些属性具有特定属性时才需要Object.defineProperties,例如不可枚举,只读或带有getter或setter函数。

There's no need to use it for normal classes and their methods, where the "simple prototype" method you describe is perfectly adequate.

没有必要将它用于普通类及其方法,其中您描述的“简单原型”方法是完全足够的。