Javascript object-oriented support (6)

Source: Internet
Author: User

========================================================== ==========================================================
Qomolangma openproject v0.9

Category: rich Web Client
Key words: JS Oop, JS framwork, rich Web Client, Ria, Web component,
Dom, dthml, CSS, JavaScript, JScript

Project Initiation: aimingoo (aim@263.net)
Project Team: aimingoo, Leon (pfzhou@gmail.com)
Contributor: Jingyu (zjy@cnpack.org)
========================================================== ==========================================================

VIII. Javascript object-oriented support
~~~~~~~~~~~~~~~~~~
(Continued)

4. instance and instance reference
--------
In. NET Framework, the rule "Everything is an object" for CTs (Common Type System) is defined as "value ".
Type and reference type. The object of "value type" is being converted to "reference type"
In the process, you need to perform a "Packing" and "unpacking" process.

The same problem occurs in JavaScript. The typeof keyword we see returns the following six data types:
"Number", "string", "Boolean", "object", "function", and "undefined ".

We also found that in the JavaScript Object System, there are four types: String, number, function, and Boolean.
Object constructor. Then, our problem is: if there is a result of the number a, typeof (),
Is it 'number' or is it an object that the constructor points to function number?

//---------------------------------------------------------
// JavaScript-type test code
//---------------------------------------------------------
Function gettypeinfo (v ){
Return (typeof v = 'object '? 'Object, construct by '+ v. Constructor
: 'Value, type of '+ typeof V );
}

VaR a1 = 100;
VaR a2 = newnumber (100 );

Document. writeln ('a1 is ', gettypeinfo (A1),' <br> ');
Document. writeln ('a2 is ', gettypeinfo (A2),' <br> ');
Document. writeln ([a1.constructor === a2.constructor, a2.constructor = number]);

The execution result of the test code is as follows:
-----------
A1 is value, type of number
A2 is object, construct by function number () {[native code]}
True, true
-----------

We noticed that both the constructors A1 and A2 point to number. This means that the constructor attribute is used to identify
Object (sometimes) is more effective than typeof. Because "value type data" A1 is treated as an object,
It has exactly the same features as A2.

-- Besides instance references.

Refer to the JScript manual to perform the same test on other basic types and constructors. We can find that:
-The undefined, number, Boolean, and string types in the basic type are "Value Type" variables.
-The array, function, and object in the basic type are "reference type" variables.
-Use the new () method to construct an object, which is a "reference type" variable.

The following code describes the differences between "value type" and "reference type:
//---------------------------------------------------------
// About the value/reference in the Javascript Type System
//---------------------------------------------------------
VaR str1 = 'abcdefgh', str2 = 'abcdefgh ';
VaR obj1 = new string ('abcdefgh'), obj2 = new string ('abcdefgh ');

Document. writeln ([str1 = str2, str1 = str2], '<br> ');
Document. writeln ([obj1 = obj2, obj1 = obj2]);

The execution result of the test code is as follows:
-----------
True, true
False, false
-----------

We can see that, whether it is equivalent operation (=) or full operation (=), for "object" and "value"
Different understandings.

To further understand this phenomenon, we know:
-If the calculation result is of the value type or the variable is of the value type, the expected result can be obtained by comparing the values (or all ).
-(Even if it contains the same data) different object instances are not equivalent (or full)
-Different references of the same object are equivalent (=) and fully equal (= ).

However, for the string type, there is a supplement: according to the description of JScript, when two strings are compared
If one is a value type, compare it by value. This means that in the above example, the code "str1 = obj1" will get
Returns true. The EQUAL (=) operation needs to check the consistency of the variable type, so the knot of "str1 = obj1"
Returns false.

Function Parameters in Javascript always input value parameters, and the reference type (Instance) is passed as the pointer value. Therefore
The function can rewrite the entry variable without worrying about the modification of the external variable. However, pay attention to the incoming references.
Type Variable, because the method call and attribute read/write may affect the instance itself. -- However, you can also
To transmit data.

At last, the value type checks the data in the object instance byte, which is less efficient but more accurate;
The reference type only detects instance pointers and data types, so the efficiency is high and the accuracy is low. If you need to detect two
Whether the reference type really contains the same data, you may need to convert it into a "string value" and then compare it.

6. Context of the Function
--------
As long as you have written code, you should know that the variables are classified into "global variables" and "local variables. The vast majority
Javascript programmers also know the following concepts:
//---------------------------------------------------------
// Global and local variables in Javascript
//---------------------------------------------------------
VaR V1 = 'Global variable-1 ';
V2 = 'Global variable-2 ';

Function Foo (){
V3 = 'Global variable-3 ';

VaR V4 = 'the local variable is used only within the function and defined by VAR ';
}

Generally, different code calls to a function have an independent set of local variables.
The following code is easy to understand:
//---------------------------------------------------------
// JavaScript local variables
//---------------------------------------------------------
Function myobject (){
VaR o = new object;

This. getvalue = function (){
Return O;
}
}

VaR obj1 = new myobject ();
VaR obj2 = new myobject ();
Document. writeln (obj1.getvalue () = obj2.getvalue ());

The result is false, indicating that the local variable "obj1/obj2" returned by different (instance methods) calls is different.

Local and global features of variables and "private" and "public" in OOP Encapsulation
The class is the same. Therefore, the vast majority of data is always described in the following way:
"Encapsulation permission level:
//---------------------------------------------------------
// OOP encapsulation in Javascript
//---------------------------------------------------------
Function myobject (){
// 1. Private Members and Methods
VaR private_prop = 0;
VaR private_method_1 = function (){
//...
Return 1
}
Function private_method_2 (){
//...
Return 1
}

// 2. Privileged Method
This. privileged_method = function (){
Private_prop ++;
Return private_prop + private_method_1 () + private_method_2 ();
}

// 3. Publish members and Methods
This. public_prop_1 = '';
This. public_method_1 = function (){
//...
}
}

// 4. Publish members and methods (2)
Myobject. Prototype. public_prop_1 = '';
Myobject. Prototype. public_method_1 = function (){
//...
}

VaR obj1 = new myobject ();
VaR obj2 = new myobject ();

Document. writeln (obj1.privileged _ method (), '<br> ');
Document. writeln (obj2.privileged _ method ());

Here, "private" indicates that only the (constructor) function can be accessed, while "privileged )"
It refers to a "public" Method for accessing a "private domain. "Public" indicates that
Data can be called and accessed.

In addition to the preceding encapsulation permissions, some documents also introduce the following two concepts:
-Prototype property: classname. Prototype. propertyname = somevalue
-(Class) Static Property: classname. propertyname = somevalue

However, from an object-oriented perspective, the above concepts are difficult to justify: What is JavaScript,
And how to divide these encapsulation permissions and concepts?

-- Because we must note the problems brought about by the following example:
//---------------------------------------------------------
// Local variables in Javascript
//---------------------------------------------------------
Function myfoo (){
VaR I;

Myfoo. setvalue = function (v ){
I = V;
}
Myfoo. getvalue = function (){
Return I;
}
}
Myfoo ();

VaR obj1 = new object ();
VaR obj2 = new object ();

// Test 1
Myfoo. setvalue. Call (obj1, 'obj1 ');
Document. writeln (myfoo. getvalue. Call (obj1), '<br> ');

// Test 2
Myfoo. setvalue. Call (obj2, 'obj1 ');
Document. writeln (myfoo. getvalue. Call (obj2 ));
Document. writeln (myfoo. getvalue. Call (obj1 ));
Document. writeln (myfoo. getvalue ());

In this test code, obj1/obj2 are all object () instances. We use function. Call ().
To call setvalue/getvalue, so that this is replaced with the obj1/obj2 instance during myfoo () call.

However, we found that after "Test 2" is complete, the parts held by obj2, obj1, and function myfoo ()
All variables return "obj2 ". -- This indicates that the three functions use the same local variable.

Javascript treats "common functions" and "constructor" separately when processing local variables.
. This processing policy is interpreted as "private domain in object oriented" in some JavaScript-related documents"
Problem. In fact, I prefer to tell you the truth at the source code level: this is the question of the context of the object.
Question. -- On the surface, the problem of "context" is passed on to the encapsulation of objects.

(Before reading the following text) give a conceptual explanation:
-In normal functions, the context is held by the window object.
-In the constructor and object method, the context is held by the object instance.

In the Javascript implementation code, each time an object is created, the interpreter creates a Context Environment for the object.
Chain is used to store a backup of the internal data of function () when an object enters the constructor and object method.
Javascript ensures that this object always holds the upper and lower attributes when it enters the constructor and object method later.
Text environment, and a related this object. Because the object may have multiple methods, and each method may save
In multi-layer nested functions, this actually forms a tree-type linked list structure in the context environment. In the constructor and
In addition to object methods, JavaScript does not provide any methods to access (the constructor and object methods) the context environment.

In short:
-The Context Environment is related to the call of the "constructor and object method" by the object instance, but not to the (common) function.
-The Context Environment records the private data of an object in the constructor and object method.
-The Context Environment uses a chained structure to record the context in multiple layers of nested Functions

Because the Context Environment is only related to the constructor and Its nested functions, read the previous code again:
//---------------------------------------------------------
// Local variables in Javascript
//---------------------------------------------------------
Function myfoo (){
VaR I;

Myfoo. setvalue = function (v ){
I = V;
}
Myfoo. getvalue = function (){
Return I;
}
}
Myfoo ();

VaR obj1 = new object ();
Myfoo. setvalue. Call (obj1, 'obj1 ');

We found that setvalue () can indeed access the "local variable I" located inside the myfoo () function, but because
The setvalue () method is implemented by the myfoo object (remember that the function is also an object), so the myfoo object has the myfoo ()
The only "context" of a function ".

Next, although the call to myfoo. setvalue. Call () passes in a new this object for setvalue (),
Objects with the "context" are still myfoo objects. Therefore, no matter how many obj1/obj2 are created
The final operation is the same private variable I.

The "context" holder of the global function/variable is window, so the following code illustrates why
Local variables can be accessed by arbitrary objects and functions ":
//---------------------------------------------------------
// Context of the global function
//---------------------------------------------------------
/*
Function window (){
*/
VaR global_ I = 0;
VaR global_j = 1;

Function foo_0 (){
}

Function foo_1 (){
}
/*
}

Window = new window ();
*/

Therefore, we can see that foo_0 () and foo_1 () can simultaneously access global_ I and global_j. The following inference is,
The Context Environment determines the global and private variables ". Instead of using the private and global variables.
Discuss the context.

Further inference is: global variables and functions in JavaScript are essentially private variables of window objects.
And methods. The context block is located in the Context Environment chain of all (within the window object) object instances.
The top of the table.

With the context theory, you can smoothly explain the global/local variables in this section"
Scope and encapsulation permissions of object methods. In fact
In the code, this "context" is called "jscontext" and serves as the first parameter of the function/method.
Input. -- If you are interested, you can verify the theory described in this section from the source code.

In addition, section 4.7 of the Javascript authoritative guide also describes this problem, but it is called a variable.
". However, it is important that this book reversed the question. -- The author tries to use global and local operations
Domain is used to explain the "context" problem that produces this phenomenon. This section is messy and difficult.
In order to justify.

However, in section 4.6.3, the author also mentioned the issue of the execution environment (Execution context ).
The "context" is consistent. However, what is more troublesome is that the author leads the readers to the wrong method and tries
Use the Context Environment of the function to explain the issues in Dom and scriptengine.

However, this book describes the query method of the "context linked list", which is correct and reasonable. Just put this
It is a bit wrong or inappropriate to call it "Scope.

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.