首页  >  文章  >  web前端  >  JavaScript 基元真的是对象吗?

JavaScript 基元真的是对象吗?

Barbara Streisand
Barbara Streisand原创
2024-11-15 00:08:02269浏览

Are JavaScript Primitives Truly Objects?

The Intriguing Nature of JavaScript Objects

In the depths of programming, the world of JavaScript presents an unexpected twist: not everything is an object. While many introductory texts hint that "almost everything" falls under this classification, a closer examination reveals a different truth.

At its core, an object encapsulates functionality through methods and properties. Arrays, for instance, fit this mold with their inherent key-value pairs. However, when it comes to "Strings", "Numbers", and "functions", the lines blur.

These entities may seem akin to functions, performing transformations on input and yielding output without apparent access to properties or methods. Dot notation remains conspicuously absent in such cases.

The Wrapper Conundrum

Unveiling the mystery, we uncover a subtle distinction: these primitives, as they are known, lack the true essence of objects. Instead, they are wrapped in object garments, namely String, Number, and Boolean. These wrappers possess methods and properties, granting the illusion of object behavior.

For example, consider this code:

var s = "foo";
var sub = s.substring(1, 2); // sub becomes "o"

Behind the scenes, JavaScript performs a series of hidden steps:

  1. Creates a String wrapper object for s, effectively applying new String(s).
  2. Executes the substring() method on the wrapper object with the specified parameters.
  3. Discards the String wrapper object.
  4. Returns the resulting string (primitive) from step 2.

The Illusion of Properties

While it appears that primitives can have properties assigned to them, such attempts prove futile as demonstrated by the following example:

var s = "foo";
s.bar = "cheese";
alert(s.bar); // undefined

This occurs because the property is defined on the ephemeral String wrapper object, which is promptly discarded, rendering the property inaccessible.

Functions: Objects in Disguise

Unlike primitives, functions are fully-fledged objects that inherit from Object. This means they possess all the capabilities of objects, including the ability to have their own properties. Witness this example:

function foo() {}
foo.bar = "tea";
alert(foo.bar); // tea

To Conclude

In JavaScript, not everything dons the mantle of an object. Primitives, disguised by object wrappers, create an illusion of object behavior. It is only through a deeper understanding of JavaScript's intricacies that the true nature of its objects becomes apparent.

以上是JavaScript 基元真的是对象吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn