There are 4 ways to create objects:
An object has properties and methods. 1. Create objects by literal valuevar person1 = { name:'Conan', age:12, sex:'male', eat:function(){ console.log("I'm hungry and want to eat") }, say:function(){ console.log("My name is Conan") } } console.log("person.eat output function",person.eat) person.eat(); //Directly output I am hungry and want to eat
2. Use the new character to create an objectvar person2 = new Object(); person2.name = 'Conan' person2.age = '21' person2.sex = 'male' person2.eat=function(){ console.log("I'm hungry and want to eat") } person2.say=function(){ console.log("My name is Conan") } console.log('sex',person2.sex) //output male The disadvantages of the above two ways to create objects:
3. Create an object with your own constructorfunction Person(name,age,sex,like){ console.log('No value is passed to the like parameter, it is undeined',like) // Here this refers to the Person object console.log('this',this) this.name=name; this.age=age; this.sex=sex; this.say=function(){ console.log("My name is",name) } } //This line of code means creating an object//Instantiating an object at the same time//And initializing the properties of this object//So this line of code is not simple let per1=new Person('Conan',19,'男'); per1.say(); console.log(per1 instanceof Person);//true Now we know that
When we create a new object, we do four things: By creating a custom object, we understand that when we create a new object, we do four things:
4. Factory pattern creates objectsfunction createObj(name,age) { let obj = new Object(); obj.name=name; obj.age=age; obj.sayHi=function(){ console.log(obj.name) } return obj; } let per=createObj('司藤',200) console.log(per.age); //200 per.sayHi(); //Si Teng This concludes this article about the four ways to create objects in JS. For more information about the four ways to create objects in JS, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
>>: Some thoughts and experience sharing on web page (website) design and production
Table of contents Achieve results Introduction to...
Table of contents Web Components customElements O...
Description of the situation: Today, I logged int...
This article uses examples to illustrate the impl...
Table of contents 1. Basic Concepts ACID 3.AutoCo...
Preface scp is the abbreviation of secure copy. s...
This article shares the MySQL installation and co...
1. Overview In the daily operation and maintenanc...
Classification of color properties Any color can ...
The specific code for JavaScript to implement the...
As shown below: XML/HTML CodeCopy content to clip...
The basic structure of HTML hypertext documents is...
This article example shares the specific code for...
1. Create the tomcat installation path mkdir /usr...
1. Introduction to Apache Bench ApacheBench is a ...