Javascript data type, object and Function

Source: Internet
Author: User
Tags getbase
1. Data Type

Javascript contains six data types: undefined, null, String, number, Boolean, and object. Among them, the first five are the original data type, and the object is the object type.

The object types include object, function, String, number, Boolean, array, Regexp, date, globel, math, and error, and the object types provided by the host environment.

2. Type Determination

Generally, JavaScript mainly uses three methods to determine the type: typeof, instanceof, and constructor.

2.1 typeof

The typeof operation may return undefined, object, number, String, function, and Boolean types. However, some cases cannot be completely accurate. For example, the value of typeof new string ('') is object.

2.2 Constructor

Sometimes we may be very lazy to use a. constructor = string for type determination, but constructor is actually unreliable. Because when we call a. constructor, the internal operation is actually toobject (a). Prototype. Constructor (what is toobject, see the following decomposition ).

See the following section.CodeYou can understand:

String.Prototype.Constructor = Number; 
Alert('Test'.Constructor = String); // Result: false

Or

Function Myclass() { 
}
Myclass.Prototype = {};
Alert((New Myclass).Constructor = Myclass); // Result: false

In addition, constructor cannot determine the inheritance relationship of the object instance type. Because JavaScript inheritance is actually implemented through the prototype chain (what is the prototype chain? See the following section for details ).

In addition, null. constructor throws the typeerror during running. Therefore, using constructor may not only be unreliable, but may also be accompanied by the risk of exceptions.

2.3 instanceof

Example: A instanceof string

Instanceof is a reliable method for object type determination. What instanceof does is to first retrieve the prototype member (string. Prototype) of the type object (string), and then compare it with the objects in the prototype chain of the object (a) to be determined one by one. Returns true if an object is found, and false if the current node in the prototype chain is null.

Type determination example: judge whether a variable is of the string type

 
Function Isstring(Str) { 
Return (Typeof Str = 'String' | Str Instanceof String);
}
3. type conversion

Ecma262 describes the following types of conversion operations: (there are other types such as toint32, which are not listed here)

    • Tonumber: Convert to number type
    • Tostring: Convert to string type
    • Toboolean: Convert to boolean type
    • Toobject: Convert to object type
    • Toprimitive: Convert to original type

Each operation describes the conversion from what type to this type of ing. For example, the above 'A'. constructor contains an implicit operation for the parser to convert 'A' to object using toobject.

Here we want to focus on toprimitive. Toprimitive is used to convert to the original data type. When the amount to be converted is already of the original type, it will be returned directly. If you want to convert an object, you can call the [[defaultvalue] Method for conversion. ([Defaultvalue]) This method can be used to input an hint parameter, which indicates that the object needs to be converted to a string or number. To convert to a string, call the tostring method of the object. to convert to a number, call the valueof method of the object. For details about the type to be converted at runtime, see the description of expression in ecma262.

----------------- Cutting line: I am tired of writing. Drink some water ----------------------

4. Object

All except the five primitive types are objects, including objects, functions, and arrays. Their instances and constructors are all objects. What is an object?

An object is an unordered member set.

It is a set that contains 0-n members. It is unordered.

Each member consists of the following three parts: name, value, and feature set.

In the following code:

VaR OBJ = {'Key': 'Value'}; 

The key is the member name, and the value is the value. The object OBJ seems to contain a member in the Code. Note that it is only in the code. We will not go into it here.

So what is a feature set?

JavaScript Object members may contain 0 or more of the following features: readonly, dontenum, dontdelete, and internal.

    • Readonly: Members with this feature cannot beProgramModified.
    • Dontenum: Members with this feature cannot be traversed by for in.
    • Dontdelete: Members with this feature cannot be deleted by the delete operation.
    • Internal: indicates that this member is an internal Member. In general, internal members cannot be accessed by the program in any way, but some JavaScript Engine implementations expose it in special ways so that some internal members of the object can be accessed.

The internal Member of an object is represented in [[xxxx.

The following lists the internal members that may be contained in objects related to the blog.

    • [[Class]: indicates the object type. For example, the value of the [[Class] member of the function object is "function"
    • [[Get] (propertyname): gets the property value of an object.
    • [[Defaultvalue] (hint): called when toprimitive performs type conversion. The possible hint value is "string" or "number"
    • [[Prototype]: [[prototype] members implement the so-called "prototype chain" in JavaScript ". The [[prototype] member of an object may be an object or null. Only the object. [[prototype] is null. The [[prototype] member of any other object is an object.
    • [[Call]: A function object-specific member. When a function is called, it is called [Call].
    • [[Construct]: The [[construct] called when a function is used as the constructor by the new operator to create an object.
    • [[Scope]: [[prototype] members implement the so-called "Scope chain" in JavaScript ".

------------------- Cutting line: the hand is sour ----------------------

5. Create a function object

When the parser encounters function declaration or function expression, it creates a function object. The steps are as follows:

    1. Parse the form parameters and function bodies
    2. Create a native ecmascript object: F
    3. Set the [[Class], [prototype], [[Call], [construct], [Scope], and length attributes of F.
    4. Create a new object (): O
    5. Set the constructor attribute of O to F.
    6. Set the prototype attribute of F to o

During the creation process, the following points should be noted:

    1. In step 3, F [[prototype] is set to function. Prototype
    2. User-Defined Functions all have the [[Call] and [construct] internal attributes at the same time.
    3. The parser automatically initializes a prototype member for each function object. F. Prototype. constructor = f. Therefore, when we do not redefine the prototype member of this f, the constructor Member of the F instance is reliable. Because (new F). constructor actually has the orientation of F. Prototype. constructor, and F. Prototype. constructor initialized to you by default by the parser is F.
    4. The [[Scope] and scope chain problems are described below

It is worth mentioning that function declaration and function expression are different.

Function declaration:

 
Function FN() {} 

Function expression:

VaR A = Function () {}; 
Function () {};

------------------- Cutting line: How is sitting so hot ----------------------

6. prototype chain

First, we need to clarify that we usually use myfunction. prototype extension, so when we hear the word "prototype chain", we will think that the "prototype" here refers to myfunction. prototype. Actually not. "prototype" refers to [prototype] of the object. Of course, the [[prototype] of an object is the current prototype member object of its real constructor.

As mentioned above, a function object created through a program will certainly contain two internal members: [[Call] and [[construct. What have they done?

[[Call]:

    1. Establish a new execution context using F's formalparameterlist, the passed arguments list, and the this value as described in 10.2.3.
    2. Evaluate F's functionbody.
    3. Exit the execution context established in step 1, restoring the previous execution context.
    4. If result (2). type is throw then throw result (2). value.
    5. If result (2). type is return then return result (2). value.
    6. (Result (2). type must be normal.) return undefined.

[[Construct]:

    1. Create a new Native ecmascript object.
    2. Set the [[Class] property of Result (1) to "object ".
    3. Get the value of the prototype property of F.
    4. If result (3) is an object, set the [[prototype] property of Result (1) to result (3 ).
    5. If result (3) is not an object, set the [[prototype] property of Result (1) to the original object prototype object as described in 15.2.3.1.
    6. Invoke the [[Call] property of F, providing Result (1) as the this value and providing the argument list passed into [[construct] As the argument values.
    7. If type (result (6) is object then return result (6 ).
    8. Return Result (1 ).

Everything is clear. When we create an object, that is, when we are new, the [[construct] member method of the function object is called. In the preceding description, Steps 3 and 4 describe the creation process of [prototype] members, that is, the prototype member of the constructor.

Okay, so when we use obj. Property to get the properties of the OBJ object, we actually call the internal method [[get] of the OBJ object. Let's see what the [[get] method call has done:

    1. If O doesn't have a property with name P, go to step 4.
    2. Get the value of the property.
    3. Return result (2 ).
    4. If the [[prototype] of O is null, return undefined.
    5. Call the [[get] Method of [[prototype] with property name p.
    6. Return result (5 ).

It can be seen that when we obtain a member of the object OBJ, we will find whether the member exists in the member of the object obj. If this parameter is not included, it is returned to OBJ. [[prototype] searches for name members in this object. If it does not exist, it goes to OBJ. [[prototype]. [[prototype] is found in this object until a [[prototype] is null. The search process is a simple task. This vine is what we call the prototype chain ".

I don't want to talk too much about the relationship and implementation between prototype chain and inheritance. There are too many materials on the network. I just want to tell you what the prototype chain is.

----------------- Cutting line: the brain is swollen ----------------------

7. function call process and scope chain

When talking about the scope chain, we need to call the function. When we have a function

 
Function FN(Param) {} 

Let's call it.

FN(1); 

What does the parser do for us at this time?

Javascript engineers with some experience may have used arguments, closures, and scopes, all of which are related to execution context.

When we call a function, the parser will create an activity object for us. Assume that the activity object is called AC (why not called AO, because C is preferred ). Then, do the following:

    1. Initialize the arguments object and add it to the AC. At this time, the object AC has a member named arguments. Here, the arguments initialization process is not specific. For more information, see section 10.1.8 of ecma262.
    2. Parse the form parameters and use the parameters passed during function calling to initialize them. In the above call example FN (1), at this time, the AC has a member named Param, and the value of this Member is 1.
    3. Initialize function declaration, create function object for all function declaration in the functionbody, and add it to the object AC as a member of the AC. In this step, it is assumed that the AC already contains an attribute of the same name and will be overwritten.
    4. Initialize the VaR declaration. For all var declarations, create a member with the same name in the object AC and initialize it as undefined. In this step, it is assumed that the AC already contains an attribute of the same name and will not be overwritten.
    5. Initialize the scope chain and associate it with the current execution context. This scope chain is a chain list. The first part is the active object AC initialized when the function is called, followed by the [[Scope] member of the function. [[Scope] is a chain. If the function body creates a function object called innerfn, the [[Scope] member of innerfn is the scope chain. When innerfn is called, a new activity object and a new scope chain will be initialized. The new scope chain is the [Scope] initialized from this new activity object and innerfn.

So what is the role of scope chain? See the description below, from 10.1.4

During execution, the syntactic production primaryexpression: identifier is evaluated using the following algorithm:

    1. Get the next object in the scope chain. if there isn't one, go to Step 5.
    2. Call the [[hasproperty] Method of Result (1), passing the identifier as the property name.
    3. If result (2) is true, return a value of type reference whose base object is Result (1) and whose property name is the identifier.
    4. Go to step 1.
    5. Return a value of type reference whose base object is null and whose property name is the identifier. we can see that when accessing a variable, we actually look for members from the scope chain related to the current execution context.

In a normal global function of a program, the value of the [[Scope] member is global object. Therefore, no matter any call, the end of the scope chain must be global object. In the browser host environment, window is used.

------------------- Cutting line: In sighs, why haven't I finished writing it? I can't stand myself anymore ----------------------

8. This in the function call Process

In function calls, what is this and its decision? In ecma262, this is a relatively winding thing, and its description is scattered all over the world.

First, the caller provides the this value in 10.2.3. if the this value provided by the caller is not an object (note that null is not an object), then the this value is the global object. we can know that caller can provide us with this. If not, this is a global object. The problem arises again. How does caller provide this?

In 11.2.3, find the following description about function CILS: The production callexpression: memberexpression arguments is evaluated as follows:

    1. Evaluate memberexpression.
    2. Evaluate arguments, producing an internal list of argument values (see 11.2.4 ).
    3. Call getvalue (Result (1 )).
    4. If type (result (3) is not object, throw a typeerror exception.
    5. If result (3) does not implement the internal [[Call] method, throw a typeerror exception.
    6. If type (Result (1) is reference, result (6) is getbase (Result (1). Otherwise, result (6) is null.
    7. If result (6) is an activation object, result (7) is null. Otherwise, result (7) is the same as result (6 ).
    8. Call the [[Call] Method on result (3), providing result (7) as the this value and providing the list result (2) as the argument values.
    9. Return result (8 ).

It can be seen from steps 6 and 7 that if the memberexpression result is a reference, this should be getbase (reference); otherwise, it is null. In step 7, the result of step 6 is the activity object, which is ignored here. I have another question. reference? What is reference and what is getbase?

We found the reference answer in 8.7. The description here is long. I just picked a section that meets our needs: a reference is a reference to a property of an object. A reference consists of two components, the base object and the property name.

The following abstract operations are used in this specification to access the components of references:

Getbase (V). returns the base object component of the reference v.

Getpropertyname (V). returns the property name component of the reference v.

Obviously, a reference must reference an attribute of an object. So we use obj. when method () is called, obj. the Method Expression generates an intermediate reference. The base object of this reference is OBJ, so the result of getbase is OBJ, so obj is provided by caller as this

I have seen manyArticleTo explain the following:

The caller provides the this value. If the this value provided by the caller is not an object (note that null is not an object), then the this value is the global object.

This is actually impossible.

Caller cannot be obj. Otherwise, it will be interpreted by the attachevent function or object method. Therefore, through the functions called by our own code, caller is determined by the execution control of the script engine; in the browser host environment triggered by an event, caller is determined by the behavior controlled by the browser.

------------------- Cutting line: stick to it, it's hard to write something positive, it's faster ----------------------

9. supplement the prototype chain-will the prototype chain be a circular chain?

This question was raised by telei. The answer is: no

Looking back at the [[construct] Step, we can find that when an object obj is created, the obj. [[prototype] member is assigned to the prototype member of its constructor. However, when the prototype member of the constructor is referenced as another object, obj. [[prototype] is still the prototype object before the constructor.

The description code is as follows)

 Function   A  (){  
This . Testa = New Function ();
}
Function B (){
This . Testb = New Function ();
}

VaR A = New A ();

B . Prototype = A ;
// A. [[prototype] =={}; (not true, {} indicates the initial prototype object of function. Same below)

VaR B = New B ();
// B. [[prototype] =;
// B. [[prototype]. [[prototype] = A. [[prototype] = {};

A . Prototype = B ;

VaR A2 = New A ();
// A2. [[prototype] = B;
// A2. [[prototype]. [[prototype] = B. [[prototype] =;
// A2. [[prototype]. [[prototype]. [[prototype] = B. [[prototype]. [[prototype] =. [[prototype] == {};

// Finally, test it. It's funny.
Alert ( A Instanceof A );

The last special explanation is: Well, the last funny thing in the code above is that it complies with the language implementation, but it is not in line with the logic of normal and abnormal people on earth. We know that object A is created by constructor A, so object A is an instance of object. However, as mentioned in the previous type determination, instanceof is determined by comparing prototype members of the constructor with the object prototype chain. So after object A is created, if the prototype of the constructor that creates it changes, a has nothing to do with its mother (constructor. Are you sure you want to change the prototype of the constructor to another object after instantiating the object?

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.