JavaScript object
JavaScript objects are data that have properties and methods.
Real life objects, properties and methods
In real life, a car is an object.
The object has its properties, such as weight and color, etc., and the methods include start and stop, etc.:
All cars have these methods, but the time they are executed is different. .All cars have these attributes, but the attributes of each car are different.
JavaScript Object
In JavaScript, almost everything is an object.
In JavaScript, objects are very important. When you understand objects, you can understand JavaScript.
#You have learned about JavaScript variable assignment.
The following code sets the value of variable car to "Fiat":
var car = "Fiat";
Object Also a variable, but an object can contain multiple values (multiple variables).
var car = {type:"Fiat", model:500, color:"white"};
In the above example, 3 values ("Fiat ", 500, "white") is assigned to the variable car.
In the above example, 3 variables (type, model, color) are assigned to the variable car.
Tip: JavaScript objects are containers for variables.
Object definition
You can define and create JavaScript objects using characters:
Example
php中文网(php.cn) 创建 JavaScript 对象。
Run the program and try it
Define JavaScript objects to span multiple lines, spaces and newlines are not necessary:
Example
php中文网(php.cn) 创建 JavaScript 对象。
Run the program and try it
Object properties
It can be said that "JavaScript objects are containers of variables".
However, we usually think of "JavaScript objects as containers of key-value pairs".
Key-value pairs are usually written as name : value (key and value are separated by colon).
Key-value pairs in JavaScript objects are often called object properties.
Tip: JavaScript objects are containers for property variables.
The object key-value pair is written similar to:
Associative array in PHP
Dictionary in Python
Hash table in C language
Hash map in Java
Hash tables in Ruby and Perl
Accessing object properties
You can access object properties in two ways:
Method one
php中文网(php.cn) 有两种方式可以访问对象属性:
你可以使用 .property 或 ["property"].
Run the program to try it
Method two
PHP中文网 有两种方式可以访问对象属性:
你可以使用 .property 或 ["property"]。
Run the program to try it
Accessing object methods
methodName : function() { code lines }You can access object methods using the following syntax:
objectName.methodName()Usually fullName() is used as a method of the person object, and fullName is used as a property. There are many ways to create, use and modify JavaScript objects. There are also many ways to create, use and modify properties and methods.