|
Post by account_disabled on Jan 25, 2024 3:38:31 GMT -5
在本文中,我将带您了解 JavaScript 对象创建的各种风格,以及每种风格如何以增量步骤构建在其他风格的基础上。 有多种用于创建对象的样式,新手和老手都会对这些选择感到不知所措,不确定应该使用哪种。但是,尽管每种语言的语法多种多样且看起来有多么不同,但它们比您可能意识到的更相似。 对象文字 我们旅程的第一站是绝对最简单的 JavaScript 对象创建方法——对象字面量。JavaScript 宣称对象可以“无中生有”地创建——没有类、没有模板、没有原型——只是噗!,一个具有方法和数据的对象:但有一个缺点。如果我们需要在其他地方创建相同类型的对象,那么我们最终将复制粘贴该对象的方法、数据和初始化。我们需要一种方法来创建不仅是一个对象,而是一系列对象。 工厂职能 JavaScript 对象创建之旅的下一站是工厂函数。这是创建共享相同结构、接口和实现的一系列对象的绝对最简单的方法。我们不是直接创建对象文字,而是从函数返回对象文字。这样,如果我们需要多次或者在多 WhatsApp 号码数据 个地方创建相同类型的对象,我们只需要调用一个函数 但有一个缺点。这种 JavaScript 对象创建方法可能会导致内存膨胀,因为每个对象都包含每个函数的唯一副本。理想情况下,我们希望每个对象只共享其函数的一份副本。 原型链 JavaScript 为我们提供了一种跨对象共享数据的内置机制,称为原型链。当我们访问对象的属性时,它可以通过委托对象仅包含该特定对象唯一的数据,并将所有其他属性请求委托给单个共享对象事实上,这是一种常见的模式,该语言内置了对其的支持。我们不需要创建自己的共享对象(原型对象)。 相反,会在每个函数旁边自动为我们创建一个原型对象,我们可以将共享数据放在那里 但有一个缺点。这将导致一些重复。该thing函数的第一行和最后一行将在每个此类委托原型工厂函数中几乎逐字重复。 类 我们可以通过将重复的行移动到自己的函数中来隔离它们。该函数将创建一个委托给其他任意函数原型的对象,然后使用新创建的对象作为参数调用该函数,最后返回该对象 事实上,这也是一种常见的模式,该语言对其有一些内置的支持。我们定义的函数create实际上是关键字的基本版本new,我们可以直接替换create为new现在我们已经到达了通常所说的“ES5 类”。它们是对象创建函数,将共享数据委托给原型对象并依赖new关键字来处理重复逻辑。 但有一个工厂函数语法,通常根本不依赖于原型链。这两种风格在性能和功能上略有不同。
|
|