JavaScript Learning Notes creating objects _javascript tips

Source: Internet
Author: User
Tags extend

JavaScript has a date, Array, string, such as the built-in objects, powerful use simple, people love, but in dealing with some complex logic, the built-in object is very weak, often need to customize the developer object.

An object is a collection of unordered attributes from a JavaScript definition, and its properties can contain basic values, objects, or functions. That is, an object is a set of properties that do not have a specific order, and each attribute is mapped to a value, a set of key-value pairs, and the value can be data or objects.

object is the basic data type of JavaScript. In JavaScript, values other than strings, numbers, true, false, NULL, and undefined are objects. Therefore, learning JavaScript not to learn to understand the object to continue to study is very difficult. Starting today into the learning of objects.

Overview

In JavaScript, an object is a basic data type, a hash on a data structure, and can be considered an unordered set of attributes, except for the original value. Everything else is an object. These values can be accessed by property names, which can be arbitrary strings that contain null characters. To put it simply, an object is a collection of attributes, one with a name (key) and a value.

To understand what a JavaScript object is, you can think about it this way. In JavaScript, an object is a curvier with attributes. Take you see a sister, this sister is an object, she has her own attributes. such as height, age, name and so on. Similarly, in JavaScript, you can use attributes to define its characteristics to an object.

Creating objects

Now that you have to learn the object, you have to have an object, so the question is, how do you create the object in JavaScript? Let's take a look at how to create objects in JavaScript.

A lot about JavaScript books in the introduction of object creation methods, mainly:

Creating objects using object literals (Key-value)

Create an object with new

To create an object using Object.create ()

creating objects using Functions

Creating objects using prototypes

Creating objects using object literals

Object literals are the simplest form of creating an object in order to simplify the process of creating objects that contain a large number of properties. An object literal consists of a mapping table of several property names (keys) and attribute values (values), with a colon (:) delimited between each pair of key/value, separated by commas (,), and the entire mapping table enclosed in curly braces ({}).

The syntax for creating an object from an object literal is as follows:

var obj = {
property_1:value_1,//property_# may be an identifier ...
2:value_2,//or a number
//..., "Property
N": value_n//or a string
};

Here obj is the name of the object being created, each property_i is an identifier (can be a name, number, or string literal), and each value_i is a value, and the value is assigned to Property_i. To see a specific example:

var girl = {
' name ': ' Xinxin ',
' age ':,
' height ': 175,
' weight '
:

This example creates an object named Girl with four property name, age, height, and weight. These four attribute pairs should have one property value.

When you create an object using object literals, you can define an object that contains only the default properties and methods if you leave the curly braces ({}) blank. Such as:

var obj = {}

When you create an object in this way, you can create an object property from a point (.), or Obj.key, to object obj and give the object a property value. You can also create object attributes by using square brackets ([]), or obj[' key ', for object obj, and assign property values to objects. As in the following example:

var girl = {};
Girl.name = ' xinxin ';
Girl.age =;
girl[' height '] = 175;
girl[' weight '] = 45;

When you print the Girl object in Chrome, the output looks like this:

Console.log (girl);
Object {name: "Xinxin", Age:18, height:175, weight:45}

Create an object with new

You can also create an object by using the new operator followed by the object constructor (with respect to the constructor, later):

var obj = new Object (); Same as Obj = {}

Although obj is an empty object in the initial state, it is easy to add and use members dynamically in JavaScript, so we can keep adding member variables and methods. Such as:

var girl = new Object ();
girl[' name ' = ' xinxin ';
Girl[' age '] =;
girl[' height '] = 175;
girl[' weight '] = 45;

To create an object using Object.create ()

Objects can also be created with the Object.create () method. This method is useful because it allows you to select its prototype object for the object you are creating, rather than defining a constructor.

The Object.create () method creates an object that has the specified prototype and several specified properties.

Object.create (Proto, [Propertiesobject])

The Object.create () method creates an object that accepts two parameters, the first of which is the object's prototype object proto, and the second is an optional argument to further describe the object's properties. This method is simple to use:

var obj1 = object.create ({
x:1,
y:2
});//Object Obj1 inherits Properties X and y
var obj2 = object.create (null);//Object Obj2 no prototypes

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 to learn more.

creating objects using Functions

In practice, the literal creation of an object is useful, but it does not meet all of our requirements, we want to be able to create a class like other background languages, and then declare instances of the class to be used more than once, without having to re-create it every time it is used.

Because JavaScript does not have classes, it is common to use functions to define a class format similar to those in other languages, such as:

function person () {
this.name = "Mary";//Add a member variable name to this class, and assign the default value to this member variable
this.age = 5;
This.sayhello = function () {
Console.log (this.name + ":" + this.age);
}

After defining the class, we can create and use objects like the following:

var person1 = new Person ();
Person1.name = ' Tom ';
Person1.age =;
Person1.sayhello (); Tom:20
var person2 = new Person ();
Person2.name = ' W3cplus ';
Person2.age = 5;
Person2.sayhello (); W3cplus:5

The person () function is not used for invocation, it is used for new.

Creating objects from prototypes

This method is the most complex and advanced method compared to the previous methods. This also involves some of the encapsulated knowledge (with regard to the subsequent learning to be recorded again). Here's a quick look at how to create an object from a prototype.

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

function person () {
this.name = "W3cplus";
This.age = 5;
This.walk = function () {
Console.log ("A Front-End site ...");}

You can then extend the membership to the outside:

Add member method
Person.prototype.sayHello = function () {
console.log ("Hello");
You can also add member properties,
Person.prototype.height = 100;

On the one hand, the prototype can extend the functionality of the original class (especially to add useful methods), or it can be written as follows:

function person () {}
Person.prototype.name = "W3cplus";
Person.prototype.age = 5;
Person.prototype.walk = function () {
Console.log ("A Front-End site ...");
Person.prototype.sayHello = function () {
console.log ("Hello");
Person.prototype.height = 100;

Property access

There are generally two ways to access object properties, the first of which is the use of dots (.) notation, which is also one of the most commonly used methods, is also a common syntax in many object-oriented languages. The second method can also use the brackets ([]) notation to access the object's properties. When using the bracket syntax, you should place the property you want to access in brackets in the form of a string. As follows:

person[' name '];
Person.name;

Functionally, there is no difference between the two methods of accessing object properties. But the main advantages of the bracket syntax are two:

Properties can be accessed through variables, as follows:

var propertyname = ' name ';
Person[propertyname];

Another advantage is that if the property name contains a character that causes a syntax error or the property name uses a keyword or reserved word, you can access the property using brackets, as follows:

person[' name '];

In general, it is recommended to use dots (.) Unless you must use it to access object properties. method to access the object properties.

Summarize

The object is the basic data type of JavaScript, it is necessary to understand the object first if you want to learn more about the JavaScript-related knowledge. This article mainly introduces several methods of creating objects. It is simpler to create by literal ({}) and new Object () methods, but the objects created by these two methods are less reusable; When you create an object with Object.create () you do not need to define a constructor to allow you to select its prototype object in the object. In addition to these methods, you can use functions and prototypes to create objects, which are relatively reusable, but are more complex to use.

JavaScript Learning notes on the creation of the object of Knowledge small series to introduce you here, I hope to help you!

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.