Home Web Front-end JS Tutorial Summary of methods for creating objects in js_javascript skills

Summary of methods for creating objects in js_javascript skills

May 16, 2016 pm 03:20 PM
js create object

There are three ways to create objects in js, here is a summary.

1. Object direct quantity

The so-called object direct quantity can be regarded as a mapping table. This method is also the most direct method. I personally recommend it,

//创建简单对象
var obj1 = {}; //空对象

var obj2 = {
  name: "ys",
  age: 12
};
//创建复杂对象
var obj3 = {
  name: "ys",
  age: 12,
  like: {
    drink: "water",
    eat: "food"
  }
};

console.log(typeof obj1);  //object
console.log(typeof obj2);  //object
console.log(typeof obj3);  //object

Copy after login

Some people may find that there are no quotation marks in the key value names here. You are very careful. In fact, you can add these quotation marks (single quotation and double quotation marks, the same as js), but I personally recommend adding them. Why? , because after adding it, the key value name can be very arbitrary... Of course, if you don’t define the name randomly, the first one is better, it varies from person to person,

var obj4 = {
  "my name": "ys",  //键值名中间有空格
  "my-age": 12,    //键值名中间有连字符
  "while": 111    //键值名是关键字
}

console.log(obj4['my name']);  //ys
console.log(obj4['my-age']);  //12
console.log(obj4.while);    //111
console.log(typeof obj3);    //object

Copy after login

Through the above example, you can see the difference between "." and "[]" access attributes

Object created by object literal, the value of key-value pair supports expressions, as follows

var obj3 = {
  name: "ys",
  age: obj2.age,   //引用obj2.age
  like: {
    drink: "water",
    eat: "food"
  }
};

console.log(obj3.age); //100

Copy after login

2.new creates object

1). System built-in objects

var obj1 = new Object();
var obj2 = new Array();
var obj3 = new Date();
var obj4 = new RegExp("ys");

console.log(typeof obj1);  //object
console.log(typeof obj2);  //object
console.log(typeof obj3);  //object
console.log(typeof obj4);  //object

Copy after login

2). Custom object

function Person(name, age){
  this.name = name;
  this.age = age;
}

var obj1 = new Person("ys", 12);

console.log(Object.prototype.toString.call(obj1));  //object
console.log(Person instanceof Object);        //true
console.log(typeof obj1);              //object
console.log(obj1.age);                //12

Copy after login

3.Object.create() creates

This method has two parameters. I will only explain the first parameter. The second parameter is not commonly used (further describe the properties of the object)
The first parameter: Pass in the prototype object to be inherited
How to understand this sentence?

var obj1 = Object.create({
  name: "ys",
  age: 12
});
console.log(obj1);     //{}
console.log(obj1.age);   //12

Copy after login

obj1 is {}, why can the attribute value be accessed? Let’s understand the meaning of the first parameter “pass in the prototype object to be inherited”

console.log(obj1.__proto__); //Object {name: "ys", age: 12}

The object itself is empty, but the data on the prototype chain is not empty. obj1.age exists, so it can be accessed.

1). When the first parameter is null

var obj2 = Object.create(null);   //不继承对象应有的属性和方法
console.log(obj2 + "abc");     //报错 ,失去 + 功能

Copy after login

Why is an error reported? The graph generated under normal parameters is as follows:

As can be seen from the figure, the prototype object (i.e. parameter) to be inherited inherits the prototype object of Object. Here is the key reason. The prototype object of Object contains some basic methods of js objects (indexOf(), toString( ), ' 'function...) At this time, if the parameter is null, then the inheritance chain is broken.

At this time, you should understand a sentence. All objects in JavaScript inherit from Object, and Object is considered to be at the top of the inheritance chain.

2). Create an empty object

var obj3 = Object.create(Object.prototype); 
console.log(obj3);              //{},(空对象,与前两个方法 {},new Object 相同)
console.log(obj3.__proto__);         //如下图 ,只包含了基本对象的方法

Copy after login

Picture of code:

The object created in this way only contains the basic methods of the object.

3). Finally, everyone looks at the following code, hoping to have a deeper understanding of the Object.create() method. You can refer to this article: 《A new way to create javascript objects Object.create()》

var obj1 = {
  name: "ys",
  age: 12
};
obj1.prototype = {
  sayName: function(){
    return console.log(this.name);
  }
};

Copy after login
/*①对象参数,只继承对象*/
var obj2 = Object.create(obj1);
console.log(obj2);                 //{}
console.log(obj2.name);               //ys
/*console.log(obj2.sayName());*/          /* 报错 obj2.sayName is not a function*/
console.log(obj2.__proto__.prototype.sayName());  //ys 理解原型的原型

Copy after login

If you don’t understand, look at the picture below

/*②对象原型,继承对象原型*/
var obj3 = Object.create(obj1.prototype);
console.log(obj3);                 //{}
console.log(obj3.name);               //undefined,没有继承对象本身
obj3.name = "ys";
console.log(obj3.name);               //ys
console.log(obj3.sayName());            //ys

Copy after login

The code does not understand the picture (picture after setting the name):

At this point I believe everyone understands the first parameter.

The above is the entire content of this article, I hope it can help you create better objects.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

How to create a family with Gree+ How to create a family with Gree+ Mar 01, 2024 pm 12:40 PM

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

How to Create a Contact Poster for Your iPhone How to Create a Contact Poster for Your iPhone Mar 02, 2024 am 11:30 AM

In iOS17, Apple has added a contact poster feature to its commonly used Phone and Contacts apps. This feature allows users to set personalized posters for each contact, making the address book more visual and personal. Contact posters can help users identify and locate specific contacts more quickly, improving user experience. Through this feature, users can add specific pictures or logos to each contact according to their preferences and needs, making the address book interface more vivid. Apple in iOS17 provides iPhone users with a novel way to express themselves, and added a personalizable contact poster. The Contact Poster feature allows you to display unique, personalized content when calling other iPhone users. you

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles