JavaScript advanced programming (version 3rd) Study Notes 6 first recognized js objects

Source: Internet
Author: User

You can put everything you want in the house. If you have enough aesthetic knowledge, you can even try a room. Of course, to facilitate management, we will give a non-repeated name to everything in the house, such as the names of various medicines in the medical room. In ECMAScript, you can store any data you want in the object. Similarly, we need to name the stored data-that is, the attribute name of the object, store various types of data. Let's look at the definition of an object in the ECMA-262: a set of unordered attributes that can contain simple data type values, objects, or functions.

I was a little excited when I started to enter the object. To tell the truth, it reminds me of the initial reason for taking this series of study notes because of the profound discussion of the object, it turned my understanding of JavaScript from the client-side verification tool into a powerful object-oriented scripting language, but now I am also a little hard, because of the object, there are too many things that need to be refined. At the moment, I don't know where to start. For example, if I want to understand objects in depth, the concepts of scope, execution environment, and closure are inevitable, however, if you haven't even mentioned the concept of an object, you can start to execute the environment and closure, and it feels like a castle in the air. However, when I think about it again, I am relieved. After all, this is just my personal study notes, and it is not a textbook. I can take my notes in my favorite way (in fact, in the previous chapter, I consciously repeat what I think is interesting. This is one of my favorite methods.) Of course, I will try to make these notes in an easy-to-understand way.

Object Type

Corresponds to five simple data types (Undefined, Null, Boolean, Number, String), and Object is also a data type, but this type of data is special, it not only can access common data like a simple data type, but also can access action behavior as a special data.

1. object instance

Each data type has a corresponding value. For example, the Undefined type has only one value undefined, and the Number 5 is a value of the Number type. For the object type, we call the value an object instance. What values can be used for all object types? Any object is an object type value (Instance). For example, a simple type packaging object (Boolean, Number, String) is an object type value (instance ).

2. Object literal volume

Since any object is an object-type instance, how does one represent an object instance? Or how can we write an object instance in the communication process? Values of the simple data type are well represented. For example, the symbol "5" represents number 5, and the symbol "true" represents the Boolean value true. These values are called literal values, is there an object literal? The answer is yes. The object literal is represented by a pair of braces. For example:
Copy codeThe Code is as follows:
{
Name: 'linjisong ',
GetName: function (){
Return this. name;
}
}

A pair of braces ({}) on the outermost layer indicates that this is an object literal. In addition, the concept of Array literal quantity also exists. In ECMAScript, Array is an Object instance that inherits the Object. Through this Object instance, you can create an Array instance, an array-type instance can also be expressed directly by the array literal. The method is as follows:
Copy codeThe Code is as follows:
[{
Name: 'linjisong ',
Age: 29
},{
Name: 'external ',
Age: 23
}]

Here, a pair of braces ([]) is used to represent an array. This is an array containing two objects. The object literal volume and array literal volume form an unimaginable powerful expressiveness. In fact, the popular JSON data format is based on this.

3. Create an object instance

Anyone familiar with General Object-Oriented Knowledge knows that to create a class instance, you must first define this class, then, use the new keyword to create an instance of this class (Don't Tell Me That reflection can be used, and my Java can't learn well ......). However, in ECMAScript, there is no class concept at all. How can we create an object instance?

Although there is no class in ECMAScript, there is a similar concept to some extent. The role is assumed by the function, you can use the new operator and function to create an object instance. Each object instance has a function used to create this instance. The most basic function is Object (), which is used to create the most common Object functions. Other functions such as Number () can be used to create instances of Number objects, Boolean () functions, an instance that can be used to create a Boolean object:
Copy codeThe Code is as follows:
Var obj = new Object (); // Object () function to create the most common Object instance
Var num = new Number (1); // Number () function to create an instance of the Number object
Var boo = new Boolean (true); // Boolean () function to create an instance of a Boolean object
Lele.info (typeof num); // object
Console.info (typeof Number (1); // number
Console.info (typeof boo); // object
Console.info (typeof Boolean (true); // boolean

(1) You can see that to create an object instance, you must first have a function (called constructor). When using the new function, you must create an object instance, when new is not used, it is only a function call in the general sense (if the function returns an instance internally, the function call can also create an object ).

(2) The so-called built-in objects are actually built-in functions for creating object instances. Different functions create different built-in objects.

(3) I suggest using the new operator or not. If the new operator is not used, the result may be unexpected in some cases, for example, rows 5th and 7 in the preceding example do not actually create an object, but are just common function calls. The function of this call is to convert the data type.

(4) When using new to create an object instance, if you do not need to input parameters when calling the constructor, you can also omit the following function call operator (). Of course, this feature is not worth promoting.

(5) To create an instance of a custom object, you must first define a constructor and then call the new operator to create an instance. Note that if you forget new, the global environment may be polluted:
Copy codeThe Code is as follows:
Function Person () {// first defines a (constructor) function used to create an object instance.
This. name = 'linjisong ';
This. age = 29;
}

Var person = new Person (); // call (constructor) to create an object instance
Console.info (person. age); // 29

Try {
Lele.info (age); // In order to demonstrate the case that you forgot to use new, the global age is output first. An exception is thrown due to undefined conditions.
} Catch (e ){
Console.info (e); // ReferenceError
}
Var person2 = Person (); // if you forget to use new, it is just a normal function call. Because the function does not return, Here person2 is undefined.
Console.info (person2); // undefined
Console.info (age); // 29, new is not used. this indicates the global scope, because age can be accessed globally.

To avoid this problem, you can modify the constructor:
Copy codeThe Code is as follows:
Function Person (){
If (this instanceof Person)
{
This. name = 'linjisong ';
This. age = 29;
} Else {
Return new Person ();
}
}
Var person2 = Person ();
Lele.info (person2.age); // 29. You can access the age of person2.
Lele.info (age); // The global environment does not have the definition of age, and an exception is thrown.


This constructor first checks whether the value of this is of the Person type. If not, it uses new internally to ensure that the returned value must be of the Person type instance. This method makes refactoring constructor possible. Maybe Boolean (), Number (), and String () are implemented in this way to distinguish between constructors and conversion functions. If you omit new when calling Object (), the results can also return objects. It is estimated that a similar process is performed in the background, in the same case, the Function Type constructor () to be discussed later in this article ().

(5) Some may ask, since there is an object literal volume, why do we need to create an object instance in such a complicated way? Simply writing the object literal volume is not enough? The preceding statement "every object instance has a function used to create this instance" is incorrect.

First of all, the first question is indeed that you can use the object literal to create a function, which is also very concise. This is even a recommended method for creating a function first, however, to create an object instance in this way, you can only create a single instance. It is not applicable to the creation of multiple object instances of the same type. The second problem is, creating an Object using the Object literal is actually not without the corresponding constructor, but the constructor is Object (). If the Object literal is used, the background may not call new Object (), however, the created object still has attributes pointing to this function, which can be verified in the following code output:
Copy codeThe Code is as follows:
Var person = {};
Console.info (person. constructor === Object); // true

Constructor is an attribute of each instance object. It is used to save the function used to create this object instance. This is what we will talk about below.

4. Object Attributes and Methods

Each data type has its own commonalities. For example, a Number type value can be added to another Number type value. Similarly, instances of the object type also have some same features. These features are embodied in the fact that they all contain the following attributes and methods (methods are actually an attribute, if the attribute value type is a function, we also call it a method ):

Category Attribute/Method Description
Attribute Constructor Point to the function used to create the current object
Method HasOwnProperty (propertyName) Check whether the specified property is in the current object instance.
PropertyIsEnumerable (propertyName) Check whether the given attribute can be enumerated using the for-in statement.
IsPrototype (object) Check whether the input object is a prototype of another object.
ToLocalString () The string of the returned object. The string corresponds to the region of the execution environment.
ToString () String Representation of the returned object
ValueOf () Returns the string, value, or Boolean value of an object, which is usually the same as the return value of the toString () method.

Note: Constructor in section 3rd of JavaScript advanced programming (version 35th) should be printed incorrectly.

There are two ways to access attributes and methods:

(1) Use the dot (.), for example, person. name.

(2) square brackets ([]): for example, person [name]. In this way, square brackets can contain a variable or expression, this allows you to access attributes and methods whose names contain special symbols.

By combining for-in with hasOwnProperty (propertyName), we can traverse the attributes of the object instance rather than those inherited from the prototype chain:
Copy codeThe Code is as follows:
For (var propertyName in object ){
If (object. hasOwnPorperty (propertyName )){
// Process cyclically
}
}

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.