JavaScript Object-oriented support (4)

Source: Internet
Author: User
Tags constructor copy empty execution functions inheritance object object variable
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

3. Structure, deconstruction and prototype issues
--------
We already know that an object needs to be generated by a constructor function. Let's first remember a few things:
-the constructor is a normal function
-prototype is an object instance
-Constructor has prototype property, object instance does not have
-(If the inheritance model is implemented properly,) the constructor property of the object instance points to the constructor
-From 三、四条: Obj.constructor.prototype point to the object's original
type

OK, so let's analyze an example to illustrate the JavaScript "inheritance prototype" declaration to
and construction process.
//---------------------------------------------------------
Examples of understanding prototypes, constructs, and inheritance
//---------------------------------------------------------
function MyObject () {
THIS.V1 = ' abc ';
}

function MyObject2 () {
This.v2 = ' def ';
}
Myobject2.prototype = new MyObject ();

var obj1 = new MyObject ();
var obj2 = new MyObject2 ();

1. The formal code for the new () keyword
------
Let's take a look at this new keyword in the line code "OBJ1 = new MyObject ()".

The new keyword is used to produce an instance (to add here, I'm used to calling the reserved word keyword.)
In addition, the New keyword is also an operator in JavaScript, but this instance should be from
A "prototype template" copied over. The prototype object used as a template is to use the constructor
The object that the prototype property of the function points to. For JavaScript "built-in object construction
, it points to a prototype inside.

Each function, regardless of whether it is used as a constructor, has a unique prototype object. Default Time
JavaScript uses it to construct an "empty initial object instance (not null)." However, if you give a letter
The prototype of the number assigns a new object, the construction process will use the new object as a "template".

Next, the construction process calls MyObject () to complete the initialization. --note that this is just "initial
of ".

To clearly explain this process, I describe the process in a formalized way:
//---------------------------------------------------------
The formal code for the new () keyword
//---------------------------------------------------------
function New (afunction) {//If there are parameters args
var _this = AFunction.prototype.clone (); Copy an object from the prototype
Afunction.call (_this); Call constructor completes initialization, (if any,) incoming args
return _this; Return object
}

So we see the following two points:
-The constructor (afunction) itself is only "initialized" to the incoming this instance, and the
Instead of constructing an object instance.
-the constructed process actually occurs inside the new () keyword/operator.

Moreover, the constructor (afunction) itself does not need to manipulate prototype and does not need to return this.


2. prototype (prototype) chain maintained by user code
------
Next we discuss the problem of the prototype chain and the construction process in more depth. This is:
-The prototype chain is created by user code, and the new () keyword does not assist in maintaining the prototype chain

For example, in the case of the Delphi code, we can use this code when declaring an inheritance relationship:
//---------------------------------------------------------
The "class" type declaration used in Delphi
//---------------------------------------------------------
Type
Tanimal = Class (TObject); Animals
Tmammal = Class (Tanimal); Mammals
Tcanine = Class (Tmammal); Mammals of the canine family
Tdog = Class (Tcanine); Dog

At this point, the Delphi compiler will compile the technology to maintain an inheritance relationship linked list. We can pass.
Query this list with code similar to the following:
//---------------------------------------------------------
Key code for using the link list in Delphi
//---------------------------------------------------------
function Isanimal (Obj:tobject): boolean;
Begin
Result: = the obj is tanimal;
End

Var
Dog: = Tdog;

// ...
Dog: = Tdog.create ();
Writeln (Isanimal (dog));

You can see that in the Delphi user code, there is no need to directly relay the link list of inheritance relationship. This is because
For Delphi is a strongly typed language, when processing with class () keyword declaring type, delphi compiler
This chain of inheritance relationships has been constructed for the user. Note that this process is a declaration, not an execution
Code.

In JavaScript, if you need to know whether the object is a subclass object of a base class,
You need to manually maintain a linked list (similar to the Delphi example). Of course, this chain has no
Called Type Inheritance tree, but called "(object) prototype linked list". --In JS, there is no "class" type.

Refer to the previous JS and Delphi code, a similar example is this:
//---------------------------------------------------------
The key code of "prototype linked list" in JS
//---------------------------------------------------------
1. Construction device
function Animal () {};
function mammal () {};
function canine () {};
function Dog () {};

2. Prototype linked list
Mammal.prototype = new Animal ();
Canine.prototype = new mammal ();
Dog.prototype = new Canine ();

3. Sample functions
function Isanimal (obj) {
return obj instanceof Animal;
}

Var
dog = new Dog ();
Document.writeln (Isanimal (dog));

As you can see, in the user code for JS, the "prototype list" is built in one line of code:
"Constructor function for current class". prototype = "instance of a direct parent class"

This differs from the language of Delphi: The essence of maintaining a prototype chain is in executing code, not declaration.

So what does it mean to be "executive rather than declarative"?

JavaScript can have a compile process. This process mainly deals with "grammar check error", "language
Legal Declaration "and conditional compilation directives". And here's the "syntax statement," which mainly deals with the letter
Several statements. And that's one reason I say "function is the first class, and object is not".

The following example:
//---------------------------------------------------------
Relationship between function declaration and execution statement (Firefox compatible)
//---------------------------------------------------------
1. Output 1234
Testfoo (1234);

2. Attempt to output obj1
3. Attempt to output obj2
Testfoo (OBJ1);
try {
Testfoo (OBJ2);
}
catch (e) {
Document.writeln (' Exception: ', e.description, ' <BR> ');
}

Declaration Testfoo ()
function Testfoo (v) {
Document.writeln (V, ' <BR> ');
}

Declaring object
var obj1 = {};
Obj2 = {
Tostring:function () {return ' Hi, object. '}
}

4. Output obj1
5. Output Obj2
Testfoo (OBJ1);
Testfoo (OBJ2);

The result of this sample code executing in the JS environment is:
------------------------------------
1234
Undefined
Exception: ' obj2 ' not defined
[Object Object]
Hi, obj
------------------------------------
The problem is that Testfoo () was executed before it was declared, and the same "direct statement"
A form-defined object variable, but cannot be referenced before the declaration. --In the example, the second to third
Input is not correct.

Functions can be referenced before they are declared, and other types of values must be declared before they can be used.
This means that "declaration" and "execution reference" are two procedures in JavaScript.

In addition, we can also find that when using "Var" to declare, the compiler will first confirm that the variable
exists, but the value of the variable will be "undefined". --So "Testfoo (obj1)" will not send
Born abnormal. However, there is no normal output until the assignment statement about OBJ1 is executed.
Please compare the difference between lines second to third and fourth to fifth.

Since JavaScript maintains the prototype chain as "execution" rather than "declaration", this means that the prototype
The chain is maintained by user code, not by the compiler.

From this inference, let's look at the following example:
//---------------------------------------------------------
Example: Wrong prototype chain
//---------------------------------------------------------
1. Construction device
function Animal () {}; Animals
function mammal () {}; Mammals
function canine () {}; Mammals of the canine family

2. Construct prototype chain
var instance = new mammal ();
Mammal.prototype = new Animal ();
Canine.prototype = instance;

3. Test output
var obj = new Canine ();
Document.writeln (obj instanceof Animal);

This output leads us to see the result of a faulty prototype chain. "Canine Feeding
Things ' are not ' an animal '.

The root cause is "2. Construct the prototype chain "the following lines of code are interpreted as executing, not like Var and
function is "declaration" and is understood at compile time. The way to solve the problem is to modify the three
Line code so that its "execution process" is logical:
//---------------------------------------------------------
Revised code for the previous example (partial)
//---------------------------------------------------------
2. Construct prototype chain
Mammal.prototype = new Animal ();
var instance = new mammal ();
Canine.prototype = instance;


3. How the prototype instance is used by the construction process
------
Still take Delphi as an example. In the construction process, Delphi will first create a specified instance size
"Empty objects," and then assign values to attributes, and invoke methods in the construction process, triggering the event
Pieces, and so on. This process is consistent with the behavior in javascript:
//---------------------------------------------------------
The construction process in JS (formal code)
//---------------------------------------------------------
function MyObject2 () {
This.prop = 3;
This.method = a_method_function;

if (you_want) {
This.method ();
This.fire_oncreate ();
}
}
Myobject2.prototype = new MyObject (); MyObject () the statement is slightly

var obj = new MyObject2 ();

If you use a single class as a reference object, JavaScript can have the same structure as the Delphi
As rich as an act. However, because the construction process in Delphi is "dynamic", the fact
Delphi also invokes the constructor of the parent class (MyObject) and the OnCreate () event that triggers the parent class.

JavaScript does not have such a feature. The construction of the parent class occurs only in the prototype (prototype
property) on the line of code that assigns the value. Thereafter, no matter how many new MyObject2 () occur,
MyObject () This constructor will not be used. -This also means:
-In the construction process, the prototype template is generated at once, and the use of this prototype instance is continuously repeated
, and no longer invokes the stereotype's constructor.

Some attributes in Delphi cannot be implemented in JavaScript because the constructor of the parent class is no longer invoked.
This mainly affects some of the events and behaviors in the construction phase. --Unable to put some "object construction process"
Code is written to the constructor of the parent class. Because no matter how many times a subclass is constructed, this object's construction process root
This does not activate the code in the parent class builder.

So once again, please look at this line in the form code of the new () keyword:
//---------------------------------------------------------
The formal code for the new () keyword
//---------------------------------------------------------
function New (afunction) {//If there are parameters args
var _this = AFunction.prototype.clone (); Copy an object from the prototype
// ...
}

In this process, JavaScript does is "Prototype.clone ()", and Delphi and other languages do
Is "inherited Create ()".

(To be continued in this section ...)



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.