JavaScript - 引用类型



JavaScript 引用类型

JavaScript 中有两种数据类型:原始类型和引用类型。

原始数据类型是不可变的,这意味着它们不能被更改。JavaScript 中的原始数据类型包括:Number、String、Boolean、Undefined、Null、Symbol。

引用数据类型是可变的,这意味着它们可以被更改。JavaScript 中的引用数据类型包括:Object、Array、Function。

当您将原始数据类型赋值给变量时,变量会获得该值的副本。当您将引用数据类型赋值给变量时,变量会获得对该值的引用。这意味着,如果您更改了引用数据类型的值,则更改将反映在所有引用该值的变量中。

例如,以下代码创建了两个变量 x 和 y,并为它们赋值 10

let x = 10;
let y = 10;

变量 x 和 y 都拥有值 10 的副本。如果您更改了 x 的值,y 的值不会改变。

x = 20;
console.log(x); // 20
console.log(y); // 10

以下代码创建了两个变量 x 和 y,并为它们赋值一个数组

const x = [1, 2, 3];
const y = x;

变量 x 和 y 都引用了同一个数组。如果您更改了 x 引用的数组的值,则更改将反映在 y 引用的数组中。

x[0] = 4;
console.log(x); // [4, 2, 3]
console.log(y); // [4, 2, 3]

了解 JavaScript 中原始类型和引用类型之间的区别非常重要,这样您才能编写出高效且可预测的代码。

对象和函数是 JavaScript 中两种主要的引用类型,解释如下。

对象

对象是键值对的无序集合,其中键是字符串或符号,值可以是任何数据类型,包括其他对象。

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

函数

函数在 JavaScript 中也是引用类型。函数是可调用的特殊类型的对象,用于执行任务。

function greet(name) {
  alert("Hello, " + name + "!");
}

示例

示例 1:对象可变性

在此示例中,我们演示了对象的可变性,首先创建一个对象,然后通过该引用进行修改,这反过来会影响原始对象。person 对象通过 anotherPerson 的引用进行修改,准确地说是年龄从 25 更改为 30。从输出中可以看到,原始对象在修改后发生了变化,因此对象被认为是发生了变异。

<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript Reference Types Example: Object Mutability</h2>
   <script>
      // Create an object
      const person = {
         name: "John",
         age: 25
      };

      // Create a reference to the object
      let anotherPerson = person;

      // Display the original object
      document.write("<p>Original Object: " + JSON.stringify(person) + "</p>");

      // Modify the object through the reference
      anotherPerson.age = 30;

      // Display the modified object
      document.write("<p>Modified Object: " + JSON.stringify(person) + "</p>");

      // Both references point to the same object, so changes are reflected in both
      document.write("<p>Original Object after modification through reference: " + JSON.stringify(person) + "</p>");
   </script>
</body>
</html>

示例 2:数组修改

此处演示了数组,数组可以在 JavaScript 中的单个变量内存储不同数据类型的多个值。它们表现出可变性,这意味着当对数组进行引用时,对引用的更改也会反映在原始数组中。这里我们创建了一个颜色的数组并通过 moreColors 的引用对其进行修改,主要是通过推送元素“yellow”。

<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript Reference Types Example: Array Modification</h2>
   <script>
      // Create an array
      const colors = ["red", "green", "blue"];

      // Create a reference to the array 
      let moreColors = colors;

      // Display the original array
      document.write("<p>Original Array: " + JSON.stringify(colors) + "</p>");

      // Modify the array through the reference
      moreColors.push("yellow");

      // Display the modified array
      document.write("<p>Modified Array: " + JSON.stringify(colors) + "</p>");

      // Both references point to the same array, so changes are reflected in both
      document.write("<p>Original Array after modification through reference: " + JSON.stringify(colors) + "</p>");
   </script>
</body>
</html>

示例 3:函数引用类型

在此示例中,我们创建了一个函数 greet,其引用最初被分配给 greetingFunction。在使用它说 Hello 后,我们将引用修改为指向一个不同的函数,该函数用 Hola 打招呼。这演示了 JavaScript 中函数引用的灵活性。

<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript Reference Types Example: Function Invocation</h2>
   <script>
      // Create a function
      function greet(name) {
         return "Hello, " + name + "!";
      }

      // Create a reference to the function
      let greetingFunction = greet;

      document.write("<p>Original Function Result: " + greetingFunction("John") + "</p>");
    
      greetingFunction = function(name) {
         return "Hola, " + name + "!";
      };

      document.write("<p>Modified Function Result: " + greetingFunction("Maria") + "</p>");
   </script>
</body>
</html>

示例 4:自定义类

此示例演示了 JavaScript 中的自定义类,从引用类型的角度来看,这是另一个关键方面。该类包含属性和函数/方法。这里我们创建一个名为 Book 的类,它具有构造函数和方法。创建了该 book 类的 4 个实例(book1、book2、book3、book4),并为其提供了相应的数据,例如标题、作者和流派。

<!DOCTYPE html>
<html>
<body>
   <h2>JavaScript Reference Types Example: Custom class</h2>
   <script>
      // Define a custom class for Book
      class Book {
         constructor(title, author, genre) {
            this.title = title;
            this.author = author;
            this.genre = genre;
         }

         // Method to get book details
         getDetails() {
            return `Title: ${this.title}<br>Author: ${this.author}<br>Genre: ${this.genre}`;
         }
      }

      // Create instances of the Book class
      const book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald", "Fiction");
      const book2 = new Book("To Kill a Mockingbird", "Harper Lee", "Classics");
      const book3 = new Book("Harry Potter and the Sorcerer's Stone", "J.K. Rowling", "Fantasy");
      const book4 = new Book("1984", "George Orwell", "Dystopian Fiction");

      document.write("<h3>Book 1 Details:</h3>");
      document.write("<p>" + book1.getDetails() + "</p>");

      document.write("<h3>Book 2 Details:</h3>");
      document.write("<p>" + book2.getDetails() + "</p>");

      document.write("<h3>Book 3 Details:</h3>");
      document.write("<p>" + book3.getDetails() + "</p>");

      document.write("<h3>Book 4 Details:</h3>");
      document.write("<p>" + book4.getDetails() + "</p>");
   </script>
</body>
</html>

示例 5:不可变对象

本示例重点关注对象的不可变性,这在创建对象时使用 `Object.freeze()` 方法实现。不可变性基本上意味着对象在创建后不会改变,或者简单地说,一旦定义了对象,就不能修改其属性。这里我们创建了一个名为“person”的对象,其属性为“name”和“age”,然后尝试将“age”更改为 35。但是,由于对象的冻结状态,此修改被阻止并抛出错误。不可变性是一个重要的方面,因为它有助于维护数据完整性,从而防止意外更改并增强代码执行的可预测性。

<!DOCTYPE html>
<html>
<body>
   <h2>Immutable Object with Error Handling</h2>
   <script>
      // Enable strict mode
      'use strict';

      // Create an immutable object
      const person = Object.freeze({
         name: "Alice",
         age: 30
      });

      document.write("<p><strong>Before Modification:</strong></p>");
      document.write("<p>Name: " + person.name + "</p>");
      document.write("<p>Age: " + person.age + "</p>");

      try {
         // Attempting to modify the object will result in an error
         person.age = 35;
      } catch (error) {
         document.write(error);
      }

      document.write("<p><strong>After Modification Attempt:</strong></p>");
      document.write("<p>Name: " + person.name + "</p>");
      document.write("<p>Age: " + person.age + "</p>");
   </script>
</body>
</html>
广告

© . All rights reserved.