JavaScript Object-oriented support (6)

Source: Internet
Author: User
Tags constructor execution functions key words variables reference variable domain
javascript| objects

======================================================================
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 launch: Aimingoo (aim@263.net)
Project team: Aimingoo, Leon (pfzhou@gmail.com)
Contributors: Jingyu (zjy@cnpack.org)
======================================================================

Eight, JavaScript object-oriented support
~~~~~~~~~~~~~~~~~~
Continued

4. Instance and instance references
--------
The. NET Framework Convention "Everything is Object" to the CTS (Common type System), and is divided into "value type" and "reference type". Where the value type object is converted to reference type data, a "boxing" and "unboxing" procedure is required.

There are similar problems in JavaScript. We see the typeof keyword, which returns the following six types of data:
' Number ', ' String ', ' Boolean ', ' object ', ' function ' and ' undefined '.

We also found that in the object system of JavaScript, there are four kinds of object constructors, string, number, Function, Boolean. So, our question is: if there is a result of a number a,typeof (a), will it be ' numbers ' or the object that a constructor points to function number ()?

//---------------------------------------------------------
Test code for types of JavaScript
//---------------------------------------------------------
function GetTypeInfo (V) {
return (typeof V = = ' object '?) ' Object, construct by ' +v.constructor
: ' Value, type of ' +typeof V ';
}

var A1 = 100;
var A2 = new number (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 results of the test code are as follows:
-----------
A1 is Value, type of number
A2 is Object, construct by function number () {[native code]}
True,true
-----------

We notice that both the A1 and the A2 constructors point to number. This means that objects are identified by constructor properties, and (sometimes) are more efficient than typeof. Because the value type data A1 is treated as an object, it has exactly the same characteristics as the A2.

--In addition to the problems associated with instance references.

Referring to the JScript manual, we do the same thing with other base types and constructors to discover:
-Undefined, number, Boolean, and string in the underlying type, the value type variable
-Array, function, and object in the underlying type, which is the reference type variable
-Use the new () method to construct an object that is a reference type variable

The following code illustrates the difference between a value type and a reference type:
//---------------------------------------------------------
About value/reference issues 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 results of the test code are as follows:
-----------
True, True
False, False
-----------

We see that both the equivalence operation (= =) and the congruent operation (= = =) have different understandings of "object" and "value".

Further understanding of this phenomenon, we know:
-When the result of the operation is a value type, or when the variable is a value type, the equivalent (or congruent) comparison can get the desired result
-(even if it contains the same data,) different object instances are not equivalent (or congruent)
-the equivalent (= =) and congruent (= = =) between different references of the same object

But for string types, there is a point of addition: according to the description of JScript, two string comparisons, as long as one is a value type, are compared by value. This means that in the above example, the code "STR1==OBJ1" will get the result true. The congruent (= = =) operation needs to detect the consistency of the variable type, so the result of "str1===obj1" returns false.

Function arguments in JavaScript always pass in the value parameter, and the reference type (the instance) is passed in as a pointer value. So the function can rewrite the entry variable at will, without having to worry about the external variable being modified. However, you need to pay attention to the variables of the incoming reference type, because the method invocation and property read and write to it may affect the instance itself. --However, you can also pass data by referring to a parameter of the type.

Finally, it is added that value type comparisons detect data in object instances byte by bit, with low efficiency but high accuracy, while reference types detect only instance pointers and data types, so they are efficient and low in accuracy. If you need to detect whether two reference types really contain the same data, you might want to try to convert it to a "string value" and compare it.


6. Context of function
--------
As long as you write code, you should know that the variables are "global variables" and "local variables". The vast majority of
JavaScript programmers also know the following concepts:
//---------------------------------------------------------
Global variables and local variables in JavaScript
//---------------------------------------------------------
var v1 = ' global variable-1 ';
v2 = ' global variable-2 ';

function foo () {
V3 = ' global variable-3 ';

var v4 = ' Only within the function and using Var defined, is a local variable ';
}

According to the usual understanding of the language, different code calls the function, it will have a set of independent local variables.
So the following code is easy to understand:
//---------------------------------------------------------
Local Variables for JavaScript
//---------------------------------------------------------
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 a different (method of instance) call is not the same.

The local and global characteristics of a variable are similar to "private" and "public" in the encapsulation of OOP. So the vast majority of information is always described in the following manner in the "Encapsulating permission level" issue in JavaScript's object-oriented systems:
//---------------------------------------------------------
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 methods
This.privileged_method = function () {
private_prop++;
return Private_prop + private_method_1 () + private_method_2 ();
}

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

4. Public 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 it is accessible only within the (constructed) function, whereas "privileges (privileged)" is specifically an open (public) method that accesses the private domain. Open (public) indicates that it can be invoked and accessed outside the (constructed) function.

In addition to the above encapsulation permissions, some of the other two related concepts are described in the documentation:
-Prototype properties: Classname.prototype.propertyName = Somevalue
-(Class) static property: ClassName.PropertyName = Somevalue

However, from an object-oriented perspective, these concepts are hard to justify: what is JavaScript, and how do you classify these encapsulation permissions and concepts?

--because we have to be aware of the problem with 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 A
MyFoo.setValue.call (obj1, ' obj1 ');
Document.writeln (MyFoo.getValue.call (obj1), ' <BR> ');

Test Two
MyFoo.setValue.call (obj2, ' obj2 ');
Document.writeln (MyFoo.getValue.call (OBJ2));
Document.writeln (MyFoo.getValue.call (obj1));
Document.writeln (Myfoo.getvalue ());

In this test code, OBJ1/OBJ2 is an object () instance. We use Function.call () to invoke Setvalue/getvalue, which replaces this as the OBJ1/OBJ2 instance during the Myfoo () call.

However, we found that after "Test two" was completed, the local variables held by Obj2, obj1, and Function Myfoo () were returned to "Obj2". -This indicates that three functions use the same local variable.

This shows that JavaScript treats a local variable with a distinction between "normal function" and "constructor". This processing strategy is interpreted as "private domain-oriented" issues in some JavaScript-related data. In fact, I prefer to tell you the truth from the source code level: This is the problem with the context of the object. But from the surface, the problem of "contextual environment" is shifted to the encapsulation of the object.

(before reading the following text,) make a conceptual note:
-In normal functions, the context is held by the Window object
-In "constructor and Object Methods", the context is held by the object instance

In the JavaScript implementation code, each time an object is created, the interpreter creates a chain of contextual chains for the object that holds a backup of the internal data for the function () when the object enters the constructor and object methods. JavaScript guarantees that this object will always hold the context, and a related this object, when it is later entered into the constructor and object methods. Since objects may have multiple methods, and each method may have a multi-tiered nested function, this in fact constitutes a tree-linked list structure of the context environment. In addition to constructors and object methods, JavaScript does not provide any method of accessing the context environment of the constructor and object methods.

Nutshell:
-The context environment is related to the invocation of the constructor and object methods by the object instance, but not to the (normal) function
-Context records the private data of an object within the constructor and object methods
-The context environment takes a chained structure to record the context in a multi-tiered nested function

Because the context only relates to the constructor and its internal nested functions, read the preceding 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 find that SetValue () does have access to "local variable i" in place within the Myfoo () function, but since the SetValue () method is Myfoo object (remember that the function is also an object), the Myfoo object has the only copy of the Myfoo () function. Context environment ".

The next MyFoo.setValue.call () call, although the new this object was passed to SetValue (), is still a Myfoo object that actually has a "context environment". So we see that no matter how many obj1/obj2 are created, the final action is the same private variable i.

The "context" Holder for global functions/variables is window, so the following code illustrates "Why global variables can be accessed by arbitrary objects and functions":
//---------------------------------------------------------
The context of the global function
//---------------------------------------------------------
/*
function Window () {
*/
var global_i = 0;
var global_j = 1;

function Foo_0 () {
}

function Foo_1 () {
}
/*
}

window = new Window ();
*/

So we can see that foo_0 () and Foo_1 () can access both global_i and Global_j at the same time. The next corollary is that context determines the "global" and "private" variables. Instead of using the private and global variables to discuss context-environment issues in turn.

The further corollary is that global variables and functions in JavaScript are essentially private variables and methods of Window objects. This context block, which is located at the top of the context list of all object instances (inside the Window object), is potentially accessible.

With the theory of context, you can successfully explain the issue of the global/local scope of variables in this section, as well as the encapsulation permissions for object methods. In fact, in the C source code that implements JavaScript, this "context" is called "Jscontext" and passed in as the first parameter of a function/method. If you are interested, you can verify the theory described in this section from the source code.

In addition, section 4.7 of the book "JavaScript Authority Guide" also covers this issue, but is called "Scope of variables." But the important thing is that the book puts the problem in reverse. The author attempts to use "global, local scope" to explain the problem of "context environment" that produces this phenomenon. So this section seems messy and hard to justify.

However, in the 4.6.3 section, the author also mentions the problem of the execution environment (execution context), which is consistent with what we are talking about as "contextual environment". More troubling, however, is the author's attempt to use the contextual context of the function to explain the problems in DOM and scriptengine by introducing the reader to the wrong way.

But the book in the "context of the list," the way the query, is correct and reasonable. Just call this "scope" a little wrong, or wrong.



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.