Javascript 简明教程

JavaScript - ES5 Object Methods

JavaScript 中的 ES5 Object methods 用于操作和保护对象。ECMAScript 5 (ES5) 是 2009 年引入的语言的重要修订版。它已向 JavaScript 添加了许多对象方法。

The ES5 Object methods in JavaScript are used to manipulate and protect the obejcts. ECMAScript 5 (ES5) is a significant revision of the language introduced in 2009. It has added many object methods to JavaScript.

这些方法为我们提供了有效的方法来遍历对象属性、操作值和对对象执行各种操作。对象操作是 JavaScript 编程的一个基本方面。

These methods provide us with efficient ways to iterate through object properties, manipulate values, and perform various operations on objects. Object manipulation is a fundamental aspect of JavaScript programming.

JavaScript ES5 Object Methods

在 ES5 中,添加了与对象相关的用于操作和保护对象的方法。下表重点介绍了对象方法及其说明 -

In ES5, object-related methods are added to manipulate and protect the objects. The following tables highlight the object methods and their descriptions −

Methods to Manipulate the Object

JavaScript 包含内置构造函数,我们已在下面的表中列出。

JavaScript contains built-in constructors, which we have listed in the below table.

Sr.No.

Method

Description

1

create()

To create new objects with specified prototype object.

2

defineProperty()

To make a clone of the object and add new properties to its prototype.

3

defineProperties()

To define a property into a particular object and get the updated object.

4

getOwnPropertyDescriptor()

To get the property descriptor for the properties of the object.

5

getOwnPropertyNames()

To get object properties.

6

getPrototypeOf()

To get the prototype of the object.

7

keys()

To get all keys of the object in the array format.

Methods to Protect the Object

Sr.No.

Method

Description

1

freeze()

To prevent adding or updating object properties by freezing the object.

2

seal()

To seal the object.

3

isFrozen()

To check if the object is frozen.

4

isSealed()

To check if the object is sealed.

5

isExtensible()

To check if an object is extensible.

6

keys()

To get all keys of the object in the array format.

7

preventExtensions()

To prevent the prototype updation of the object.

让我们在几个示例的帮助下理解上面列出的每种方法——

Let’s undertand each of the methods listed above with the help of some examples −

JavaScript Object.create() Method

JavaScript Object.create() 方法会创建一个具有指定原型对象和属性的新对象。它是 JavaScript 中的一个静态方法。

The JavaScript Object.create() method creates a new object with the specified prototype object and properties. It is a static method in JavaScript.

JavaScript 中 Object.create() 方法的语法如下——

The syntax of the Object.create() method in JavaScript is as follows –

Object.create(proto, propertiesObject)

Object.create() 方法中的参数如下——

The paramters in the Object.create() method are as follows −

  1. proto − it is the object that is used as prototype of new object.

  2. propertiesObejct (optaional) − It’s an object that defines the properties of new object.

Example

在下面的示例中,student 对象是使用 person 对象作为其原型而创建的。

In the example below, the student object is created using the person object as it’s prototype.

<html>
<body>
  <div id = "output"> </div>
  <script>
    const person = {
      firstName: "John",
      lastName: "Doe"
    };

    const student = Object.create(person);
    student.age = 18;

    document.getElementById("output").innerHTML =
    student.firstName + "<br>" +
    student.lastName + "<br>" +
    student.age;

  </script>
</body>
</html>
John
Doe
18

JavaScript Object.defineProperty() Method

您可以使用 Object.definedProperty() 方法定义对象的单个属性或更新该属性的值和元数据。它是 JavaScript 中的一个静态方法。

You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata. It’s a static method in JavaScript.

JavaScript 中 Object.definedProperty() 方法的语法如下——

The syntax of the Object.definedProperty() method in JavaScript is as follows −

Object.defineProperty(obj, prop, descriptor)

Object.defineProperty() 方法的参数如下:

The paramters in the Object.definedProperty() method are as follows −

  1. obj − it is the object on which the property is to be defined or modified.

  2. prop (string or symbol) − It’s the name of property to be defined or modified.

  3. descriptor − It’s an object that defines the property’s attributes.

Example

以下示例包含汽车对象的 brand、model 和 price 属性。我们使用 defineProperty() 方法在对象中定义了 'gears' 属性。

The below example contains the car object’s brand, model, and price properties. We used the defineProperty() method to define the 'gears' property in the object.

<html>
<body>
    <div id = "output">The obj object is - </div>
    <script>
        const car = {
            brand: "Tata",
            model: "Nexon",
            price: 1000000,
        }

        Object.defineProperty(car, "gears", {
            value: 6,
            writable: true,
            enumerable: true,
            configurable: true
        })

        document.getElementById("output").innerHTML += JSON.stringify(car);
    </script>
</body>
</html>
The obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}

JavaScript Object.defineProperties() Method

JavaScript 中的 Object.defineProperties() 方法是一个静态方法,可以定义对象的属性或修改属性。

The Object.defineProperties() method in JavaScript is a static method that defines new properties of object or modifies the properties.

JavaScript 中 Object.defineProperties() 方法的语法如下:

The syntax of Object.defineProperties() method in JavaScript is as follows –

Object.defineProperties(obj, props)

Object.defineProperties() 方法的参数如下:

The parameters in the Object.defineProperties() method are as follows −

  1. obj − it is the object on which the properties are to be defined or modified.

  2. prop (string or symbol) − It’s the name of property to be defined or modified.

Example

在以下示例中,我们使用 Object.defineProperties() 方法添加了两个名为 property1 和 property2 的属性。property1 是可写的,property2 是不可写的。

In the following example, we use Object.defineProperties() method to add two mew properties named property1 and property2. The property1 is writable and property2 is non-writable.

<html>
<body>
  <div id = "output"> </div>
  <script>

    const object1 = {};

    Object.defineProperties(object1, {
      property1: {
        value: 42,
        writable: true,
      },
      property2: {
      value: "Tutorials Point",
      writable: false,},
    });

    document.getElementById("output").innerHTML =
    "Property1 : "  + object1.property1 + "<br>" +
    "Property2 : "  + object1.property2;

  </script>
</body>
</html>
Property1 : 42
Property2 : Tutorials Point

JavaScript Object.getOwnPropertyDescriptor() Method

JavaScript 中的 Object.getOwnPropertyDescriptor() 方法返回一个指定对象属性的属性描述符。返回的属性描述符是一个 JavaScript 对象。

The Object.getOwnPropertyDescriptor() method in JavaScript returns a property descriptor for a specific property of an object. The returned property descriptor is a JavaScript object.

Example

尝试以下示例:

Try the following example −

<html>
<body>
  <div id = "output"> </div>
  <script>

    const object1 = {
      property1: 42,
    };

    const descriptor1 = Object.getOwnPropertyDescriptor(object1, 'property1');

    document.getElementById("output").innerHTML =
    "descriptor configurable? : "  + descriptor1.configurable + "<br>" +
    "descriptor value : "  + descriptor1.value;

  </script>
</body>
</html>
descriptor configurable? : true
descriptor value : 42

JavaScript Object.getOwnPropertyNames() Method

JavaScript 中的 Object.getOwnPropertyNames() 方法返回给定对象中所有属性的数组。这包括可枚举和不可枚举属性。

The Object.getOwnPropertyNames() method in JavaScript returns an array of all the properties found in a given object. This includes both enumerable and non-enumerable properties.

Example

在以下示例中,我们使用 getOwnPropertyNames() 方法获取已创建对象的属性名称。

In the example below, we use getOwnPropertyNames() method to get the property names of the created object.

<html>
<body>
  <div id = "output"> </div>
  <script>
    const obj = {
      a: 10,
      b: 20,
      c: 30,
    };
    document.getElementById("output").innerHTML = Object.getOwnPropertyNames(obj);
  </script>
</body>
</html>
a,b,c

JavaScript Object.getPrototypeOf() Method

JavaScript 中的 Object.getPrototypeOf() 方法返回指定对象的原型。它是 ES5 中添加的静态 JavaScript 方法。

The Object.getPrototypeOf() method in JavaScript returns the prototype of the specified object. It’s a static JavaScript method added in ES5.

Example

<html>
<body>
  <div id = "output"> </div>
  <script>
    const prototype1 = {name: "John Doe"};
    const object1 = Object.create(prototype1);
    const prot = Object.getPrototypeOf(object1)
    document.getElementById("output").innerHTML = JSON.stringify(prot);
  </script>
</body>
</html>
{"name":"John Doe"}

JavaScrip Object.keys() Method

Object.keys() 方法在 javaScript 中把对象作为参数并且返回一个包含对象自己的可枚举属性名称的数组。

The Object.keys() method in javaScript takes an object as an argument and returns an array containing the object’s own enumerable property names.

<html>
<body>
  <div id = "output"> </div>
  <script>
     let person = {
       name: "John Doe",
       age: 20,
       profession: "Software Engineer"
      };

    document.getElementById("output").innerHTML = Object.keys(person);
  </script>
</body>
</html>
name,age,profession

JavaScript Object.freeze() Method

JavaScript 中的 Object.freeze() 是一个静态方法,它冻结了一个对象。冻结的对象不能再被改变。不能添加任何新属性,不能移除现有属性。不能修改属性的值。

The Object.freeze() in JavaScript is static method that freezes an object. A frozen object can not be further changed. No new property can be added or the existing properties can not be removed. The values of the properties can not be modified.

<html>
<body>
  <div id = "output"> </div>
  <script>
    const obj = {
      prop: 23,
    };

    Object.freeze(obj);
    // obj.prop = 33;
    // Throws an error in strict mode
    document.getElementById("output").innerHTML = obj.prop;
  </script>
</body>
</html>
23

JavaScript Object.seal() Method

Object.seal() 静态方法密封了一个对象。在一个密封的对象中,不能添加任何新属性,也不能删除任何属性。

The Object.seal() static method seals an object. In a sealed object, no new property can be added, no property can be deleted.

<html>
<body>
  <div id = "output"> </div>
  <script>
    const obj = {
      property: 34,
    };

    Object.seal(obj);
    obj.property = 33;
    document.getElementById("output").innerHTML = obj.property;

    delete obj.property; // Cannot delete when sealed

    document.getElementById("output").innerHTML = obj.property;
  </script>
</body>
</html>
33

JavaScript Object.isFrozen() Method

JavaScript 中的 Object.isFrozen() 方法如果给定的对象被冻结则返回 true,否则如果对象没有被冻结则返回 false。

The Object.isFrozen() method in JavaScript returns true if the given object is frozen, else it returns false if the object is not frozen.

<html>
<body>
  <div id = "output1"> </div>
  <div id = "output2"> </div>
  <script>
    const person = {
      age: 21,
    };
    document.getElementById("output1").innerHTML = Object.isFrozen(person);
    // Expected output: false
    Object.freeze(person);
    document.getElementById("output2").innerHTML += Object.isFrozen(person);
    // Expected output: true
  </script>
</body>
</html>
false
true

JavaScript Object.isSealed() Method

JavaScript 中的 Object.isSeal() 方法用于检查给定的对象是否已密封。如果对象已密封,则返回 true,否则返回 false。

The Object.isSeal() method in JavaScript is used to check if the given object is sealed or not. It returns true if the object is sealed else it retuens flase.

<html>
<body>
  <div id = "output1"> </div>
  <div id = "output2"> </div>
  <script>
    const person = {
      name: "John Doe",
    };
    document.getElementById("output1").innerHTML = Object.isFrozen(person);
    // Expected output: false
    Object.seal(person);
    document.getElementById("output2").innerHTML += Object.isSealed(person);
    // Expected output: true
  </script>
</body>
</html>
false
true

JavaScript Object.preventExtensions() Method

ES5 中的 Object.preventExtensions() 方法用于阻止更新对象的原型。它还会阻止向对象添加新属性。

The ES5 Object.preventExtensions() method is used to prevent the prototype updation of an object. It also prevent the new properties to be added to an object.

<html>
<body>
  <div id = "output"> </div>
  <script>
    const person = {};
    Object.preventExtensions(person);
    try {
      Object.defineProperty(person, 'name', {
        value: "John Doe",
      });
    } catch (e) {
      document.getElementById("output").innerHTML =e;
    }
  </script>
</body>
</html>

它将生成如下输出:

It will produce the following output −

TypeError: Cannot define property name, object is not extensible

JavaScript Object.isExtensible() Method

JavaScript 中的 Object.isExtensible() 方法用于检查一个对象是否可扩展。如果返回 true,则表示给定的对象可扩展,否则返回 false。如果可以向对象添加新属性,则该对象是可扩展的。

The JavaScript Object.isExtensible() method is used to check if an object is extensible or not. It returns true indicating the given object is extensible, else it will return false. An object is extensible if it can have new properties added to it.

<html>
<body>
  <div id = "output1"> </div>
  <div id = "output2"> </div>
  <script>
    const person = {
      name: "John Doe",
    };

    document.getElementById("output1").innerHTML = Object.isExtensible(person);
    // Expected output: false
    Object.preventExtensions(person);
    document.getElementById("output2").innerHTML += Object.isExtensible(person);
    // Expected output: false
  </script>
</body>
</html>
true
false