Objects

Javascript Objects (Javascript对象)

Defining JavaScript Objects

Defining JavaScript Objects (定义JavaScript对象)

Generally, JavaScript is known as an Object Oriented Programming language. Hence, in JavaScript, objects are the most important data types and forms. They are entirely different from primitive data types in JavaScript. As it was mentioned in the the chapter “Data types”, there are seven data types in JavaScript, six of which are called “primitive” as their values include a single thing ( it can be a number, a string, etc.). (通常, JavaScript被称为面向对象编程语言。因此,在JavaScript中,对象是最重要的数据类型和表单。它们与JavaScript中的原始数据类型完全不同。正如在“数据类型”一章中提到的那样, JavaScript中有七种数据类型,其中六种被称为“原始” ,因为它们的值包括一个东西(可以是数字、字符串等)。)

Unlike data types, we use objects for storing keyed collections of different data and more complicated entities. In JavaScript, objects are included in all aspects of the language, so you need to learn them as soon as you start to study the language. (与数据类型不同,我们使用对象来存储不同数据和更复杂实体的键控集合。在JavaScript中,对象包含在语言的各个方面,因此您需要在开始学习语言时立即学习它们。)

Objects are created with figure brackets {…} and should have a list of properties. Property is known as a “key: value”, in which key or property name is a string and value can be whatever.

You can create an empty object running one of the following syntaxes:

let user = new Object(); // "object constructor" syntax
let user = {}; // "object literal" syntax

As a rule, figure brackets {…} are used. This declaration is called object literal.

Properties and Literals

Properties and Literals (属性和文字)

You can instantly input properties in that brackets as pairs of “key: value”, like this:

let site = {  // an object
 name: "w3cdoc", // by key "name" store value "w3cdoc"
};
console.log(site);

site has one property : the name “name” and the value “w3cdoc”.

Property values can be accessed using dot notation, as follows:

let site = { // an object
 name: "w3cdoc", // by key "name" store value "w3cdoc"
};
// get property values of the object:
console.log(site.name); // w3cdoc

It can have any type of value. For example:

let site = { // an object
 name: "w3cdoc", // by key "name" store value "w3cdoc"
};
site.haveAdmin = true;
console.log(site);

delete operator is used is used for deleting a property. For instance:

let site = { // an object
 name: "w3cdoc", // by key "name" store value "w3cdoc"
 haveAdmin: true
};
delete site.name;
console.log(site);

Multiword property names can also be used. But they need to be quoted like this:

let user = {
 site: "w3cdoc",
 "teaches JS": true // multiword property name must be quoted
};
console.log(user);

End the last property of the list with a comma:

let site = {
 name: "w3cdoc",
 haveAdmin: true,
}
console.log(site);

Square Brackets

Square Brackets (方括号)

The dot access doesn’t operate for multiword properties. Here is an example:

// this would give a syntax error
site.teaches JS = true

The dot needs the key for being a valid variable identifier. It means no limitations, such as spaces, etc. (点需要密钥作为有效的变量标识符。这意味着没有任何限制,例如空格等。)

You can use an alternative square bracket notation. It will operate with any string. For instance:

let site = {};
// set
site["teaches JS"] = true;
// get
console.log(site["teaches JS"]); // true
// delete
delete site["teaches JS"];
console.log(site);

With the help of the square brackets, you can keep the property name as a result of any expression like this:

let site = {};
let key = "teaches JS";
// same as site["teaches JS"] = true;
site[key] = true;
console.log(site);

In this case, the variable key can either be measured at run time or lean on the user input. Then you can use it for accessing the property as follows:

let site = {
 name: "w3cdoc",
};
let key = prompt("What do you want to know about the site?", "name");
console.log(site[key]); // If enter "name", you will see w3cdoc

Note that you can’t use the dot notation similarly:

let site = {
 name: "w3cdoc"
};
let key = "name";
console.log(site.key) // undefined

Computed Properties

Computed Properties (计算属性)

Square brackets are also used in an object literal. It is known as computed properties. (方括号也用于对象文本中。它被称为计算属性。)

Here is an example:

let car = prompt("Which car do you like?", "bmw");
let color = {
 [car]: "white", // the property's name is taken from the variable car
};
console.log(color.bmw); // white, if car="bmw"

You can also use more complicated expressions in square brackets, like this:

let car = 'bmw';
let carColor = {
 [car + 'Color']: 'white' // carColor.bmwColor = 'white'
};
console.log(carColor.bmwColor); // white

So, when the name of the property is simple and known, you can use dots. And when you need something more complicated, then turn to square brackets. (因此,当房源名称简单且已知时,您可以使用点。当您需要更复杂的东西时,请转向方括号。)

Shorthand for Property Value

Shorthand for Property Value (属性值的速记)

In real code, existing variables are often used as property name values. (在实际代码中,现有变量通常用作属性名称值。)

Here is an example:

function makeCar(name, model) {
 return {
   name: name,
   model: model,
   // ...other properties
(其他属性)
 };
}
let car = makeCar("BMW", "M5");
console.log(car.name); // BMW
function makeCar(name, model) {
 return {
   name, // same as name: name
   model // same as model: model
   // ...
(//...)
 };
}

Both normal properties and shorthands can be used in the framework of the same project. It will look like this:

let car = {
 name, // same as name:name
 model: "M5"
};
console.log(car);

The “for…in” loop

The “for…in” loop (“for… in”循环)

The “for…in” loop is a unique form of a loop. It’s totally different from the for(;;).

The syntax is the following:

for (key in object) {
 // executes the body for each key among object properties
}

Let’s have a look at an example, where all properties of car are output:

let car = {
 name: "Mercedes",
 model: "C-Class Cabriolet",
 toDrive: true
};
for (let key in car) {
 // keys
(关键)
 console.log(key); // name, model, toDrive
 // values for the keys
(//键的值)
 console.log(car[key]); // Mercedes, C-Class Cabriolet, true
}

Take into account that all the constructs of “for” gives an opportunity to declare the looping variable in the loop. For example, let key in the example given above. Another variable name can also be used instead of the key. (考虑到“for”的所有构造都提供了在循环中声明循环变量的机会。例如,在上面给出的示例中键入。也可以使用另一个变量名代替键。)

Checking Existence

Checking Existence (检查是否存在)

One of the most significant advantages of objects is that it gives access to any property. No error will occur, in case the property doesn’t exist. If you access a non-existing property, you will be returned to undefined. It gives a unique opportunity of checking the property exists or not:

let car = {};
console.log(car.noSuchProperty === undefined); // true means "no such property"

You can use a unique operator “in” as well for checking a property existence. To run it, use the following syntax:

"key" in object

Copy by Reference

Copy by Reference (按型号(Ref.))

One of the principal differences objects via primitives is that they can be stored and copied by reference. (通过基元对象的主要区别之一是它们可以通过引用来存储和复制。)

You can assign/copy primitive values (strings, numbers, booleans) as an entire value. Just look at this example:

let message = "Welcome to w3cdoc!";
let phrase = message;
console.log(phrase);

In consequence, you will have two independent variables; each of them will store the string “Welcome to w3cdoc!”.

Objects don’t work like that. (对象不是这样工作的。)

A variable will store not the object but its “address in memory”. In other words, it stores just a reference to it. (变量将不存储对象,而是存储其“内存中的地址”。换句话说,它只存储对它的引用。)

For instance:

let car = {
 name: "BMW"
};
console.log(car);

Where the object is in the memory, and the variable car contains a reference to it. Anytime you copy an object variable, you duplicate the reference, but the object is not copied. (对象在内存中的位置,可变CAR包含对其的引用。每次复制对象变量时,都会复制引用,但不会复制对象。)

For example:

let car = {
 name: "BMW"
};
let sportCar = car; // copy the reference
console.log(sportCar);

Comparing by Reference

Comparing by Reference (按引用比较)

In JavaScript, two objects can be considered equal only in case they are the same object. (在JavaScript中,只有当两个对象是同一个对象时,才能将其视为相等。)

For example, two variables are equal when they reference the same object:

let obj1 = {};
let obj2 = obj1; // copy the reference
console.log(obj1 == obj2); // true, both variables reference the same object
console.log(obj1 === obj2); // true

In the following case, the two independent objects can’t be considered equal, even though both of them are empty:

let obj1 = {};
let obj2 = {}; // two independent objects
console.log(obj1 == obj2); // false

Const object

Const object (Const对象)

An object that is proclaimed const can be changed. Here is an example:

const car = {
 name: "BMW"
};
car.model = "M5"; // (*)
console.log(car.model); // M5

You may think that the (*) will give an error, but there is no error here. You will wonder why. The reason is that const can fix only value of car. It will cause an error only while trying to set car to something else like this:

const car = {
 name: "BMW"
};
// Error (can't reassign car)
car = {
 name: "Mercedes"
};
console.log(car);

Clone and Merge, Object.assign

Clone and Merge, Object.assign (克隆和合并, Object.assign)

To copy an object variable means to create another reference to the same object. (复制对象变量意味着创建对同一对象的另一个引用。)

But what to do when you need to duplicate the object? (但是,当您需要复制对象时该怎么办?)

Of course, you can clone it, but it is not an easy job, as JavaScript doesn’t have a built-in method. So, whenever you need to do so, create a new object replicating its structure and iterating over the properties and copy them on the primitive level. The example is as follows:

let car = {
 name: "BMW",
 model: "M5"
};
let cloneObj = {}; // the new empty object
// start copying all properties of the car into it
for (let key in car) {
 cloneObj[key] = car[key];
}
// now clone is a fully independent clone
cloneObj.name = "BMW"; // changed the data in it
console.log(car.name); // still BMW in the original object

The Object.assign method is used for that, as well. You just need to use the following syntax:

Object.assign(dest, [src1, src2, src3...])

It can also be used for merging several objects:

let car = {
 name: "BMW"
};
let resolve1 = {
 canDrive: true
};
let resolve2 = {
 canChange: true
};

// duplicates overall properties from resolve 1 and resolve2 into car
Object.assign(car, resolve1, resolve2); // now car = { name: "BMW", canDrive: true, canChange: true }
console.log(car);

In JavaScript, objects are much more powerful than it can seem from the first sight. This is an extensive topic, and you will learn more about it in the next chapters. (在JavaScript中,对象比一开始看起来要强大得多。这是一个广泛的主题,您将在接下来的章节中了解有关它的更多信息。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部