This is the 22nd day of my participation in the August More Text Challenge

Hi, I’m Ken

Author: Please call me Ken Link: juejin.cn/user/109118… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

🌊🌈

Part of the content and pictures of the article are from the Internet. If you have any questions, please contact me (there is an official account in the introduction of the home page).

This blog is suitable for just contactJSAnd the friends who want to review after a long time.

🌊🌈

JavaScript object

5.1_ Initial Object

5.1.1_ What is an object

For example, if you describe a cell phone object in JavaScript, the cell phone has the following properties and methods:

  • Phone attributes: color, weight, screen size.
  • Cell phone methods: call, send text messages, watch videos, listen to music. In code, an attribute can be thought of as a variable held in an object, using object. Attribute name “represents; A method can be thought of as a function stored in an object, using object. Method name () “to access.
// Suppose we now have a cell phone object p1, created in code
var p1 = {
color: 'black'.weight: '188g'.screenSize: '6.5'.call: function (num) {
console.log('Call up'+num);
},

sendMessage: function (num, message) {
console.log ('to'+ num + 'Send a text message saying :' + message);
},

playVideo: function() {
console.log ('Play video');
},

playMusic: functlon() {
console.log ('Play music'); }};// access the attributes of p1
console.log (pl.color);     // Output result :" black ", indicating that the color of the mobile phone is black
console.log (p1.weight);    // Output: "188g", which means the weight of the phone is 188g
console.log (p1.screenSize);// Output :"6.5", indicating that the screen size of the phone is 6.5 inches

// call p1's method
p1.call('123');           // Call the phone number 123
p1.sendMessage('123'.'hello'); // Text the phone number 123 with the message hello
p1.playVideo();    // Call the phone's playback video method
p1.playMusic();    // Call the phone's play music method
Copy the code

As you can see from the above code, object properties and variables are used similarly, and object methods and functions are used similarly. Objects are a collection of properties and methods, represented by a simple variable name p1.

5.1.2_ Create objects using literals

In JavaScript, object literals are the members of the object wrapped in curly braces “{“. Each member is stored in the form of “key: value”, where key denotes the name of the property or method and value denotes the corresponding value. Multiple object members are separated by commas (,).

Case study:

// Create an empty object
var obj = {};
// Create a student object
var stul = {
name: 'Ming'./ / the name attribute
age: 18./ / the age attribute
sex: 'male'./ / sex properties

sayHello: function () {  / / sayHello method
console.log ('Hello'); }};Copy the code

In the code above, obj is an empty object that has no members. Stu1 contains four members: name, age, sex, and sayHello. Name, age, and sex are attribute members, and sayHello is a method member.

5.1.3_ Access object properties and methods

Once the object is created, you can access its properties and methods. Example code is as follows:

// Access the attributes of the object (syntax 1)
console.log (stul.name);   // Output result: Xiao Ming
// Access the attributes of the object (syntax 2)
console.log (stul['age']); // Output :18

// Call a method on an object (syntax 1)
stul.sayHello();        // Output: Hello
// Call a method on an object (syntax 2)
stul['sayHello'] ();// Output: Hello
Copy the code

If the member name of an object contains special characters, it can be represented as a string, as shown in the following code:

var obj = {
'name-age': 'xiao Ming - 18'
};
console.log (obj['name-age']);  
// Output result :" xiaoming-18"
Copy the code

JavaScript objects are dynamic. If an object has no members, users can manually assign attributes or methods to add members, as shown in the following example:

varStu2 = {};// Create an empty object
stu2.name = 'Jack';  // Add the name attribute to the object
stu2.introduce = function() {     // Add the introduce method to the object
alert ('My name is ' + this.name);// Use this in the method to represent the current object
};

alert (stu2.name);// Access the name attribute, output: Jack
stu2.introduce();// Call the rule introduce(), output :My name is Jack
Copy the code

In the code above, the object itself can be represented as this in its methods, so the name attribute of the object can be accessed using this.name.

Undefined is returned when accessing properties that do not exist in the object. Example code is as follows:

var stu3 = {};      // Create an empty object
console.log(stu3.name); // Output result: undefined
Copy the code

5.1.4 creating an Object with the New Object

When we learned about arrays, we knew that we could use new Array to create Array objects. An array is a special Object. If you want to create a normal Object, use a New Object.

Example code is as follows:

var obj = new Object(a);// Create an empty object
obj.name = 'Ming';  // After the object is created, add members to it
obj.age = 18;
obj.sex = 'male';
obj.sayHello = function(){
console.log('Hello');
};
Copy the code

5.1.5_ Create objects using constructors

The literals we learned earlier are only suitable for creating one object, but when creating multiple objects, we need to write each member of the object, which is cumbersome. Therefore, we can use constructors to create objects. The syntax for using constructors to create objects is “new constructor name ()”, in which arguments can be passed to the constructor in parentheses, or the parentheses can be omitted if there are no arguments.

In effect, “new Object()” is a way to create an Object using the constructor, Object being the name of the constructor, but this creates an empty Object.

The basic syntax is as follows:

// Write the constructor
functionConstructor name () {
this.attribute = attribute;thisDirection:.function() {
/ / the method body
};
}

// Use the constructor to create an object
var obj = newConstructor name ();Copy the code

In the above syntax, this in the constructor represents the newly created object, and this can be used to add members to the newly created object in the constructor. Note that constructor names are recommended to start with a capital letter.

Case study:

// Write a Student constructor
function Student (name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log ('Hello, my name is.' + this.name);
};
}

// Create an object using the Student constructor
var stul = new Student('Ming'.18);
console.log(stul.name);         // Output result: Xiao Ming
console.log(stu1.sayHello());   // Output result: Hello, my name is Xiao Ming
var stu2 = new Student('little red'.17);
console.log(stu2.name);         // Output result: small red
console.log(stu2.sayHello());   // Output result: Hello, my name is Xiao Hong
Copy the code

Constructors in JavaScript are similar to classes in traditional object-oriented languages such as Java, so some of the terms of object-oriented programming can be used in JavaScript as well.

  • Abstract: The process of extracting the common features of a class of objects and writing them into a constructor (class) is called abstraction.
  • Instantiation: The process of creating an object using a constructor (class), called instantiation.
  • Instance: If the STU1 object is created by the Student constructor, the stu1 object is called an instance (or instance object) of the Student constructor.

Tip: In some documentation, it is common to refer to methods on objects as functions, or to constructors as constructors or constructors, just to understand that these names refer to the same thing.

Learn more: Static members

There is a concept of static in object-oriented programming, and JavaScript is no exception. Static members in JavaScript are properties and methods that are inherent in constructors and can be used without creating instance objects.

Static member creation and use are shown in the following code:

function Student(){
}

Student.school = 'x university';       // Add the static property school
Student.sayHello = function() { // Add static method sayHello
console.log('Hello');
};

console.log(Student.school);    // Output result :x university
Student.sayHello();             // Output :Hello
Copy the code

5.1.6_ Traversal object properties and methods

You can iterate over all properties and methods in an object using the for.in syntax, as shown in the following example:

// Prepare an object to be traversed
var obj = {name:'Ming'.age:18.sex:'male'};

// Iterate over the obj object
for(var k in obj){
// Use k to get the attribute name or method name in the traversal process
console.log(k);        // Output :name, age, sex
console.log (obj[k]);  // Output: xiao Ming, 18, male
}
Copy the code

In the above code, k is a variable name that can be customized, conventionally named k or key to indicate the key name. As each member is traversed, use k to get the name of the current member and obj[k] to get the corresponding value. Alternatively, if the object contains a method, it can be called with “obj[k] ()”.

Learn more: Check whether object members exist

We can use the in operator when we need to determine whether a member of an object exists, for example:

var obj = (name:'Tom'.age: 16);
console.log('age' in obj);   // Output result: true
console.log('gender' in obj);// Output result: false
Copy the code

As you can see from the above code, the object returns true if a member exists and false if it does not.

That’s the end of today’s introductory study

Peace

🌊🌈

A Ken HTML, CSS introduction guide (a)_HTML basics a Ken HTML, CSS introduction guide (b)_HTML page elements and attributes a Ken HTML, CSS introduction guide (c)_ text style attributes Ken HTML, CSS introduction guide (four)_CSS3 selector Ken HTML, CSS introduction guide (five)_CSS box model Ken HTML, CSS introduction guide (six)_CSS box model Ken HTML, CSS introduction guide (seven)_CSS box model Ken’s Getting Started with HTML and CSS (8)_CSS box model Ken’s Getting Started with HTML and CSS (9)_ Floating and Positioning Ken’s Getting Started with HTML and CSS (10)_ Floating and Positioning Ken’s getting Started with HTML and CSS (11)_ Floating and positioning Ken’s introduction to HTML and CSS (12)_ The application of forms The introduction to HTML and CSS (13)_ the application of forms (14)_ the application of forms the introduction to HTML and CSS (15)_ the application of forms A Ken HTML, CSS introduction guide (16) _ multimedia technology

Suggest collection 】 【 HTML dry share | challenge the shortest possible time to take you into the HTML (18) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (19) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (20)

Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (a) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (2) suggest collection 】 【 share | JS dry challenge the shortest time to take you into the JS (3) the share | JS dry Recommended collection 】 challenge the shortest time take you into the JS (4) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (5) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (6)

🌊🌈 About postscript:

Thank you for reading, I hope to help you if there is a flaw in the blog, please leave a message in the comment area or add contact information in the home page of the personal introduction of private chat I thank every little partner generous advice

Original is not easy, “like” + “attention” thanks for your support ❤