Javascript 简明教程
JavaScript - Objects Overview
JavaScript Objects
JavaScript object 是一种非原始数据类型,用于将数据存储为 key-value 对。键值对通常称为属性。键值对中的键,也称为“属性名称”,是一个字符串,值可以是任何东西。如果某个属性的值是一个函数,则该属性称为 method 。
The JavaScript object is a non-primitive data type that is used to store data as key-value pairs. The key-value pairs are often referred as properties. A key in a key-value pair, also called a "property name", is a string and value can be anything. If a property’s value is a function, the property is known as a method.
使用花括号创建对象,每个属性用逗号分隔。每个属性都写为属性名称,后跟冒号 (:),后跟属性值。键:值对不会按特定顺序存储在对象中。所以对象是一个无序的属性集合,写为键:值对。
Objects are created using curly braces and each property is separated by a comma. Each property is written as property name followed by colon (:) followed by property value. The key: value pairs are not stored in the specific order in the object. So an object is an unordered collection of properties written as key: value pairs.
JavaScript 是一种面向对象编程 (OOP) 语言。如果一种编程语言为开发者提供了四种基本能力,则可以称其为面向对象的。
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers.
-
Encapsulation − the capability to store related information, whether data or methods, together in an object.
-
*Abstraction * − the capability to hide object’s implementation details from users.
-
Inheritance − the capability of a class to rely upon another class (or number of classes) for some of its properties and methods.
-
Polymorphism − the capability to write one function or method that works in a variety of different ways.
让我们详细了解 JavaScript 对象。
Let’s understand in details about the JavaScript objects.
Object Properties
对象属性可以是任何原始数据类型、对象或函数。对象属性通常是在对象的方法中内部使用的变量,但也可以是整个页面中使用的全局可见变量。
Object properties can be any of the primitive data types, objects or functions. Object properties are usually variables that are used internally in the object’s methods, but can also be globally visible variables that are used throughout the page.
向对象添加属性的语法为:
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − 以下代码使用 document 对象的 "title" 属性获取文档标题。
For example − The following code gets the document title using the "title" property of the document object.
var str = document.title;
Object Methods
方法是让对象做某事或让某些事对对象执行的函数。函数与方法之间存在小差异 - 函数是一个独立的语句单元,而方法依附于对象,并且可以由 this 关键字引用。
Methods are the functions that let the object do something or let something be done to it. There is a small difference between a function and a method – at a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.
这些方法对从显示对象内容到屏幕到对一组局部属性和参数执行复杂数学运算的所有内容都很有用。
Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.
For example - 以下是一个简单的示例,展示如何使用文档对象的 write() 方法写入文档中任何内容。
For example − Following is a simple example to show how to use the write() method of document object to write any content on the document.
document.write("This is test");
Creating New Objects
所有用户定义的对象和内置对象都是 Object 对象的后代。
All user-defined objects and built-in objects are descendants of an object called Object.
我们可以使用对象字面量来创建新的用户定义对象。或者,我们可以创建一个构造函数,然后使用 new 关键字调用此函数来实例化一个对象。
We can use object literals to create a new user-defined object. Alternatively, we can create a constructor function and then invoke this function using new keyword to instantiate an object.
在 JavaScript 中创建对象有不同的方法。在此,我们学习以下给定方法。
There are different ways to create an object in JavaScript. Here, we will learn all ways given below.
-
Using the Object Literal
-
Using the Object Constructor
-
Using the Object.create() Method
-
Using JavaScript ES6 Classes
The JavaScript Object Literal
在 JavaScript 中,“{}”由对象字面量表示。您可以在大括号之间添加键值对对来定义对象。
In JavaScript, ‘{}’ is represented by the object literal. You can add pair of key-value pairs between curly braces to define an object.
您可以按照以下语法使用对象字面量来定义对象。
You can follow the syntax below to use the object literal to define objects.
const obj = {
key: val,
}
您可以在大括号内添加键值对。每个键值对由逗号分隔,并且您需要在键和值之间添加一个冒号 (:)。
You can add key-value pairs between curly braces. Each key-value pair is comma separated, and you need to add a colon (:) between the key and value.
在下面的示例中,我们定义了一个包含 4 个属性的 wall 对象。每个属性都包含不同数据类型的值。
In the example below, we have defined a wall object containing the 4 properties. Each property contains the different values of different data types.
在输出中,您可以观察对象属性及其值。
In the output, you can observe the object properties and its value.
<html>
<body>
<p id = "output"> </p>
<script>
const myBook = {
title: "Perl",
author: "Mohtashim",
pages: 355,
}
document.getElementById("output").innerHTML =
"Book name is : " + myBook.title + "<br>"
+"Book author is : " + myBook.author + "<br>"
+"Total pages : " + myBook.pages;
</script>
</body>
</html>
Book name is : Perl
Book author is : Mohtashim
Total pages : 355
The JavaScript new Operator
new 运算符用于创建对象的实例。要创建对象,new 运算符后面跟构造函数方法。
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
在以下示例中,构造方法为 Object()、Array() 和 Date()。这些构造函数是内置的 JavaScript 函数。
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The JavaScript Object() Constructor
构造函数是创建并初始化对象的函数。JavaScript 提供了一个名为 Object() 的特殊构造函数来构建对象。Object() 构造函数的返回值分配给一个变量。
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.
变量包含对新对象的引用。分配给对象的属性不是变量,也不使用 var 关键字定义。
The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.
尝试以下示例;它演示如何创建对象。
Try the following example; it demonstrates how to create an Object.
<html>
<body>
<p id = "output"> </p>
<script>
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
document.getElementById("output").innerHTML =
"Book name is : " + book.subject + "<br>" +
"Book author is : " + book.author;
</script>
</body>
</html>
Book name is : Perl
Book author is : Mohtashim
The JavaScript Constructor Function
在 JavaScript 中,您可以定义一个自定义函数并将其用作构造函数来定义一个新对象。在这里,自定义函数充当模板。
In JavaScript, you can define a custom function and use it as a constructor function to define a new object. Here, the custom function works as a template.
自定义用户定义构造函数比 Object() 构造函数的好处在于您可以根据您的要求向自定义函数添加参数。
The benefit of the custom user-defined constructor function over the Object() constructor is that you can add arguments to the custom function according to your requirements.
以下是使用自定义用户定义构造函数创建对象的简单语法。
Below is simple syntax to use the custom user-defined constructor function to create an object.
// Object template
function ConstructorFunc(para) {
this.para = para;
}
const obj = new ConstructorFunc(arg);
ConstructorFunc() 函数充当对象模板。它使用 'this' 关键字来访问函数的上下文并在函数上下文中定义键。此外,键使用 'para' 值初始化。
The ConstructorFunc() function works as an object template. It uses the 'this' keyword to access the context of the function and define the key in the function context. Also, the key is initialized with the 'para' value.
接下来,您可以将函数作为带有 'new' 关键字的构造函数使用,以定义对象并将所需参数传递给构造函数。
Next, you can use the function as a constructor with a 'new' keyword to define the object and pass the required arguments to the constructor.
此示例演示如何使用用户定义的构造函数 Function 创建对象。此处使用 this 关键字来引用已传递给函数的对象。
This example demonstrates how to create an object with a user-defined constructor Function. Here this keyword is used to refer to the object that has been passed to a function.
<html>
<body>
<div id = "output"> </div>
<script>
function Book(title, author) {
this.title = title;
this.author = author;
}
const myBook = new Book("Perl", "Mohtashim");
document.getElementById("output").innerHTML =
"Book title is : " + myBook.title + "<br>" +
"Book author is : " + myBook.author + "<br>";
</script>
</body>
</html>
Book title is : Perl
Book author is : Mohtashim
The JavaScript Object.create() Method
Object.create() 方法从已经定义的对象中创建一个新对象。此外,您还可以在使用 Object.create() 方法从另一个对象克隆一个对象时向对象原型中添加一些新属性。
The Object.create() method creates a new object from the already defined object. Also, you can add some new properties to the object prototype while cloning one object from another object using the Object.create() method.
按照以下语法使用 Object.create() 方法定义新对象。
Follow the syntax below to use the Object.create() method to define a new object.
const obj = Object.create({}, {
key: { value: val },
})
-
{} − It is an empty object. The Object.create() method creates a copy of it.
-
{ key: { value: val }, } − It is an object containing the properties to add to the prototype of the cloned object.
在下面的示例中,我们向空对象的原型添加了多个属性。但是,如果您打印对象,您将无法看到任何属性,因为它们被添加到原型中。
In the example below, we added multiple properties to the prototype of the empty object. However, if you print the object, you won’t be able to see any properties as they are added to the prototype.
您可以使用点表示法访问对象属性。
You can access the object properties with a dot notation.
<html>
<body>
<p id = "output"> </p>
<script>
const myBook = Object.create({}, {
title: { value: "Perl" },
author: { value: "Mohtashim" },
})
document.getElementById("output").innerHTML =
"Book title is : " + myBook.title + "<br>" +
"Book author is : " + myBook.author + "<br>";
</script>
</body>
</html>
Book title is : Perl
Book author is : Mohtashim
The JavaScript ES6 Classes
ES6 中引入了 JavaScript 类。JavaScript 类是用于创建对象的模板。使用“class”关键字定义类。它类似于在定义类时的函数。class 关键字后跟类名,然后是类主体。
The JavaScript classes are introduced in ES6. The JavaScript classes are template to create objects. A class is defined using the "class" keyword. It is similar to the function while defining a class. The class keyword is followed by the class name and then class body.
class MyClass{
//class body
}
可以使用 new 运算符使用类创建对象 -
You can use the new operator to create an object using a class −
const myObj = new MyClass();
此处 ClassName 是类的名称,而 myObject 是使用此类创建的对象的名称。
Here ClassName is the name of class and myObject is the name of object creating using this class.
我们在下一章中详细讨论了 JavaScript 类。
We have discussed the JavaScript classes in details in the next chapter.
Defining Methods for an Object
前面的示例演示了构造函数如何创建对象并分配属性。但是我们需要通过向其分配方法来完成对对象的定义。
The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.
Example
尝试以下示例;它显示如何将一个函数与一个对象一起添加。
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script>
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
function Book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<div id = "output"> </div>
<script>
var myBook = new Book("Perl", "Mohtashim");
myBook.addPrice(100);
document.getElementById("output").innerHTML =
"Book title is : " + myBook.title + "<br>"
+"Book author is : " + myBook.author + "<br>"
+"Book price is : " + myBook.price + "<br>";
</script>
</body>
</html>
The 'with' Keyword
‘with’ 关键字用作引用对象属性或方法的一种速记。
The ‘with’ keyword is used as a kind of shorthand for referencing an object’s properties or methods.
作为 with 的参数指定的对象成为随后块的默认对象。可以在没有使用对象名称的情况下使用对象的属性和方法。
The object specified as an argument to with becomes the default object for the duration of the block that follows. The properties and methods for the object can be used without naming the object.
Syntax
with object 的语法如下 -
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Example
尝试以下示例。
Try the following example.
<html>
<head>
<script>
// Define a function which will work as a method
function addPrice(amount) {
with(this) {
price = amount;
}
}
function Book(title, author) {
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<div id = "output"></div>
<script>
var myBook = new Book("Perl", "Mohtashim");
myBook.addPrice(100);
document.getElementById("output").innerHTML =
"Book title is : " + myBook.title + "<br>"
+"Book author is : " + myBook.author + "<br>"
+"Book price is : " + myBook.price + "<br>";
</script>
</body>
</html>
JavaScript Native Objects
JavaScript 有几个内置的或本地的对象。这些对象可以访问程序的任何地方,并且在运行于任何操作系统中的任何浏览器中都将以相同的方式工作。
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program and will work the same way in any browser running in any operating system.
以下是所有重要的 JavaScript 本地对象列表 -
Here is the list of all important JavaScript Native Objects −
JavaScript Object Methods
在此,我们列出了 JavaScript 对象的方法。
Here, we have listed the methods of JavaScript object.
Static methods
这些方法是使用 Object 类本身调用的。
These methods are invoked using the Object class itself.
Sr.No. |
Method |
Description |
1 |
assign() |
To copy properties and their values from one object to another object. |
2 |
create() |
To create a new object using an existing object as prototype. |
3 |
defineProperty() |
To make a clone of the object and add new properties to its prototype. |
4 |
defineProperties() |
To define a property into a particular object and get the updated object. |
5 |
entries() |
It returns an array containing the [key, value] pairs. |
6 |
freeze() |
To prevent adding or updating object properties by freezing the object. |
7 |
fromEntries() |
To create a new object from the array of the [key, value] pairs. |
8 |
getOwnPropertyDescriptor() |
To get the property descriptor for the properties of the object. |
9 |
getOwnPropertyNames() |
To get object properties. |
10 |
getOwnPropertySymbols() |
To get all symbols in the array form which are present in the object. |
11 |
getPrototypeOf() |
To get the prototype of the object. |
12 |
hasOwn() |
To check whether the particular property exists in the object. |
13 |
Object.is() |
To check whether the two objects contain a similar value. |
14 |
isExtensible() |
To check if an object is extensible. |
15 |
isFrozen() |
To check if the object is frozen. |
16 |
isSealed() |
To check if the object is sealed. |
17 |
keys() |
To get all keys of the object in the array format. |
18 |
preventExtensions() |
To prevent the prototype updation of the object. |
19 |
seal() |
To seal the object. |
20 |
setPrototypeOf() |
To set a prototype of the object. |
21 |
toLocaleString() |
To get the object in the string format. |
22 |
values() |
To get all values of the object in the array format. |
Instance methods
这些方法是使用对象的实例调用的。
These methods are invoked using the instance of the object.
Sr.No. |
Method |
Description |
1 |
defineGetter() |
To define getters to get the particular property value. |
2 |
hasOwnProperty() |
To check if the object has a particular property as its own property. |
3 |
isPrototypeOf() |
To check whether the particular object exists as a prototype of the other object. |
4 |
propertyIsEnumerable() |
To check whether the property of the object is enumerable. |