How to Create object_javascript in JavaScript learning notes

Source: Internet
Author: User
In JavaScript, an object is a basic data type. It is a hash in the data structure and can be seen as an unordered set of attributes. Everything except the original value is an object. This article mainly introduces the creation objects of JavaScript learning notes. For more information, see the built-in objects such as Date, Array, and String in JavaScript. This article is powerful and easy to use, however, when dealing with some complex logic, the built-in object is very weak, and developers often need to customize the object.

In JavaScript definition, an object is a set of unordered attributes. Its Attributes can contain basic values, objects, or functions. That is to say, an object is a group of attributes with no specific order. Each attribute is mapped to a value, which is a group of key-value pairs. The value can be data or an object.

Objects are the basic data types of JavaScript. In JavaScript, values except strings, numbers, true, false, null, and undefined are all objects. Therefore, it is very difficult to learn JavaScript without learning objects. Start learning objects today.

Overview

In JavaScript, an object is a basic data type. It is a hash in the data structure and can be seen as an unordered set of attributes. Everything except the original value is an object. These values can be accessed through the attribute name, and the attribute name can be any string including null characters. Simply put, an object is a set of attributes. An attribute contains a name (key) and a value (value ).

You can understand what JavaScript objects are. In JavaScript, an object is an attribute-specific entity. Take the girl you see. This girl is an object and has her own attributes. For example, Sister height, age, name, etc. Similarly, in JavaScript, attributes can be used to define its features for objects.

Create object

Now that you want to learn objects, you must first have an object. The problem arises. How can we create objects in JavaScript? Next let's take a look at how to create objects in JavaScript.

Many JavaScript Books introduce how to create objects:

Create an object using the object literal (key-value)

Use new to create an object

Use Object. create () to create an Object

Use functions to create objects

Create an object using a prototype

Create an object using the object literal

Object literal is the simplest form of object creation. It aims to simplify the process of creating an object containing a large number of attributes. The object literal is a ing table consisting of several attribute names (keys) and attribute values (values). keys and values are separated by colons, each pair of key/value is separated by commas (,), and the entire ing table is enclosed by curly brackets.

Syntax:

Var obj = {property_1: value_1, // property _ # may be an identifier... 2: value_2, // or a number //..., "property n": value_n // or a string };

Obj is the name of the created object. Each property_ I is an identifier (which can be a name, number, or string literal) and each value_ I is its value, and assign this value to property_ I. Let's look at a specific instance:

Var girl = {'name': 'sinhin', 'age': 18, 'height': 175, 'weight': 45}

In this example, an object named girl is created. The object has four attributes: name, age, height, and weight. These four attributes correspond to an attribute value.

When using object literal to create an object, if you leave its curly braces ({}) blank, you can define an object that contains only the default attributes and methods. For example:

var obj = {}

When using this method to create an object, you can use the dot (.), that is, obj. key, to create an object attribute for the object obj and assign the property value to the object. Alternatively, you can use square brackets ([]), that is, obj ['key'], to create object attributes for object obj and assign the object attribute values. Example:

Var girl = {}; girl. name = 'xin xin'; girl. age = 18; girl ['height'] = 175; girl ['weight '] = 45;

When the girl object is printed in Chrome, the output result is as follows:

Console. log (girl); // Object {name: "xin", age: 18, height: 175, weight: 45}

Use new to create an object

You can also create an Object by using the new operator followed by the Object constructor (for more information about constructor:

Var obj = new Object (); // The same as obj = {}

Although obj is an empty object in the initial state, it is easy to dynamically add and use members in JavaScript, so we can add member variables and Methods continuously. For example:

Var girl = new Object (); girl ['name'] = 'xin xin'; girl ['age'] = 18; girl ['height'] = 175; girl ['weight'] = 45;

Use Object. create () to create an Object

You can also use Object. create () to create an Object. This method is very useful because it allows you to select a prototype object for the created object without defining a constructor.

The Object. create () method creates an Object with the specified prototype and several specified attributes.

Object. create (proto, [propertiesObject])

Object. the create () method creates an object and accepts two parameters. The first parameter is the prototype object proto of this object, and the second parameter is an optional parameter, it is used to further describe the attributes of an object. This method is easy to use:

Var obj1 = Object. create ({x: 1, y: 2}); // The Object obj1 inherits the attributes x and yvar obj2 = Object. create (null); // The object obj2 has no prototype.

If the proto parameter is not null or an object value, a TypeError exception is thrown.
For more examples of the Object. create () method, click here.

Use functions to create objects

In actual use, creating objects literally is very useful, but it cannot meet all our needs. We hope to create a class like other background languages, then the declared class instance can be used multiple times, instead of re-creating it every time it is used.

Because JavaScript does not have a class, it generally uses functions to define a class format similar to that in other languages, such:

Function Person () {this. name = "mary"; // Add a member variable name for this class and assign the default value this to this member variable. age = 5; this. sayHello = function () {console. log (this. name + ":" + this. age );};}

After defining the class, we can create and use objects as follows:

var person1 = new Person();person1.name = 'Tom';person1.age = 20;person1.sayHello(); // Tom : 20var person2 = new Person();person2.name = 'W3cplus';person2.age = 5;person2.sayHello(); // W3cplus : 5

The Person () function is not called, but used by new.

Create an object through a prototype

Compared with the previous methods, this method is the most complex and advanced method. Some encapsulated knowledge is also involved here (there are further records of these follow-up learning ). Here is a simple example of how to create an object through a prototype.

First, define a function like a function method to create an object:

Function Person () {this. name = "W3cplus"; this. age = 5; this. walk = function () {console. log ("a front-end website... ");};}

Then, the members can be expanded externally:

// Add the member method Person. prototype. sayHello = function () {console. log ("hello") ;}; // You can also add member attributes, Person. prototype. height = 100;

On the one hand, the prototype can expand the functions of the original class (especially add useful methods), or write as follows:

Function Person () {} Person. prototype. name = "W3cplus"; Person. prototype. age = 5; Person. prototype. walk = function () {console. log ("a front-end website... ") ;}; Person. prototype. sayHello = function () {console. log ("hello") ;}; Person. prototype. height = 100;

Attribute access

There are two methods to access object attributes. The first method is dot (.) notation, which is also the most common method and the common syntax in many object-oriented languages. The second method can also use brackets ([]) to access object attributes. When you use the brackets syntax, you should place the attributes to be accessed in brackets in the form of strings. As follows:

person['name'];person.name;

In terms of functions, there is no difference between the above two methods to access object attributes. However, the brackets have two main advantages:

You may access attributes through variables as follows:

var propertyName = 'name';person[propertyName];

Another advantage is that if the attribute name contains characters that may cause syntax errors or the attribute name uses keywords or reserved words, you can use brackets to access the attribute, as shown below:

Person ['first name'];

Generally, we recommend that you use the dot (.) method to access object attributes unless you must use the method to access object attributes.

Summary

Objects are the basic data type of JavaScript. To learn more about JavaScript, it is necessary to fully understand the objects. This article mainly introduces several methods for creating objects. The simple method is to create an Object by using the literal ({}) and new Object () methods, but the reusability of the objects created by the two methods is poor. create () allows you to select a prototype object in an object without defining a constructor when creating an object. In addition to these methods, you can also use functions and prototypes to create objects. These two methods are relatively reusable, but complex to use.

This is a small part of the knowledge about creating objects in JavaScript learning notes. I hope it will be helpful to you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.