Javascript object-oriented Support (2)

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)
========================================================== ==========================================================

2) reflection mechanism implementation in Javascript
------
In JavaScript, the reflection mechanism is implemented through the for... in syntax. But JavaScript does not
Clearly differentiate "attributes", "methods", and "events ". Therefore, the attribute type is checked in JS
Is a problem. The following code is a simple example of the use of for... in and attribute recognition:
//---------------------------------------------------------
// Use and attribute recognition of for. In in Javascript
//---------------------------------------------------------
VaR _ r_event =/^ [oo] n .*/;
VaR colorsetting = {
Method: 'red ',
Event: 'blue ',
Property :''
}

VaR obj2 = {
A_method: function (){},
A_property: 1,
Onclick: Undefined
}

Function propertykind (OBJ, p ){
Return (_ r_event.test (p) & (OBJ [p] = undefined | typeof (OBJ [p]) = 'function '))? 'Event'
: (Typeof (OBJ [p]) = 'function ')? 'Method'
: 'Properties ';
}

VaR objectarr = ['window', 'obj1'];

For (VAR I = 0; I <objectarr. length; I ++ ){
Document. writeln ('<p> for', objectarr [I], '<HR> ');

VaR OBJ = eval (objectarr [I]);
For (var p in OBJ ){
VaR kind = propertykind (OBJ, P );
Document. writeln ('obj. ', P,' is A', kind. fontcolor (colorsetting [kind]), ':', OBJ [p], '<br> ');
}

Document. writeln ('</P> ');
}

A fact that is often overlooked by developers is that JavaScript itself has no event system. Connect
The onclick and other events we often use in JavaScript are actually provided by the DOM model of IE. From more Kernel
From the perspective of: IE publishes a group of event interfaces to Dom through the interface attribute of COM.

There are two reasons that make it difficult to identify "whether an attribute is an event" in JS ":
-The COM interface only contains methods, attributes, and events, which are published through a set of get/set methods.
-In JavaScript, there is no independent "Event" mechanism.

Therefore, we can see that the event recognition method is to check whether the attribute name starts with the 'on' string (open with 'on ').
). Next, because the event in the DOM object can not specify the handler function
In this case, the event handle is null (qomo adopts the same conventions). In other cases, you can
An event with a value of undefined can be defined like obj2. Therefore, the condition for determining the "event" is handled.
Into a complex expression:
("Attributes starting with on/on" & ("value: NULL/undefined" | "type: function "))

In addition, we can see from the running result of the above Code. If you use for... in for DOM objects, you cannot list them.
Object method.

Last, I will explain it. In fact, in the implementation of many languages, "events" are not "object-oriented ".
It is provided by a specific programming model. For example, the event-driven mechanism in Delphi is
The window message mechanism in the operating system is provided, or the user code actively calls the message in component/class.
Event processing functions.

"Event" is a mechanism/problem of "how to drive the programming model", rather than the language itself. However
The concept of OOP Based on PME (property/method/event) is deeply rooted in the hearts of the people.
When these features are presented, no one cares about "who implemented the event.

3) use of this and with keywords
------
In the JavaScript Object System, this keyword is used in two places:
-In the constructor function, it refers to the newly created object instance.
-When an object method is called, it refers to the object instance that calls the method.

If a function is called as a common function (rather than an object method), The this keyword in the function
Will point to the window object. Similarly, if the this keyword is not in any function, it also points
Window object.

Because JavaScript does not clearly distinguish between functions and methods. So some code looks strange:
//---------------------------------------------------------
// Several possible call forms of functions
//---------------------------------------------------------
Function Foo (){
// The following this refers to the object instance that calls this method.
If (this = Window ){
Document. Write ('Call a function. ',' <br> ');
}
Else {
Document. Write ('Call a method, by object: ', this. Name,' <br> ');
}
}

Function myobject (name ){
// The following this indicates the New Keyword used to create an instance.
This. Name = Name;
This. Foo = Foo;
}

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

// Test 1: called as a function
Foo ();

// Test 2: Call the object Method
Obj1.foo ();
Obj2.foo ();

// Test 3: Call a function as the "specified object" Method
Foo. Call (obj1 );
Foo. Apply (obj2 );

In the above Code, the call of obj1/obj2 to Foo () is a very common call method. --
Is a method that specifies a function as an object on the constructor.

The call () and apply () in Test 3 are special.

In this test, Foo () is still called as a common function, but it is only a language feature of JavaScript.
When call ()/apply () is enabled, an object instance is passed in to specify
This keyword reference. -- Note that Foo () is still a common
Function call, rather than object method call.

Similar to this "object instance that instructs to call this method", The with () syntax is also used to limit
"Object instances are used by default in a code snippet ". -- If the with () syntax is not used
This code will be affected by the with () Statement; if there is no with () statement (),
The "Default object instance used" in this code will be window.

However, it should be noted that this and with keywords do not affect each other. The following code:
//---------------------------------------------------------
// Test: This and with keywords do not affect each other
//---------------------------------------------------------
Function Test (){
With (obj2 ){
This. value = 8;
}
}
VaR obj2 = new object ();
Obj2.value = 10;

Test ();
Document. writeln ('obj2. Value: ', obj2.value,' <br> ');
Document. writeln ('window. Value: ', window. value,' <br> ');

You cannot expect this code to set the obj2.value attribute to 8 after the call is complete. These rows
The result of the Code is that the window object has an additional value attribute and the value is 8.

With (OBJ) {...} this syntax can only limit the reading of existing properties of OBJ, rather than the active
Declare it. Once the object in with () does not have a specified attribute, or with () limits a non-pair
The result is an exception.

4). operations using the in keyword
------
In addition to using for... in to reflect the object's member information, JavaScript also allows the direct use of in
Keyword to check whether the object has the attribute of the specified name.

The reason why the in keyword is often mentioned is not its ability to detect the existence of attributes. Therefore, in the early stage
In the Code, many may like to use "If (! OBJ. propname) {} "to detect propname
Whether it is a valid attribute. -- In many cases, detection is more effective than checking whether the property exists.
It is practical. Therefore, in is an optional and official solution.

An important application of the in keyword is high-speed string retrieval. In particular, you only need to determine whether the string is
If yes. For example, if 0.1 million strings are stored in an array, the retrieval efficiency will be
Very poor.
//---------------------------------------------------------
// Search by Object
//---------------------------------------------------------
Function arraytoobject (ARR ){
For (var obj = new object (), I = 0, IMAX = arr. length; I <IMAX; I ++ ){
OBJ [arr [I] = NULL;
}
Return OBJ;
}

VaR
Arr = ['abc', 'def ', 'ghi']; // more and more...
OBJ = arraytoobject (ARR );

Function valueinarray (v ){
For (VAR I = 0, IMAX = arr. length; I <IMAX; I ++ ){
If (ARR [I] = V) return true;
}

Return false;
}

Function valueinobject (v ){
Return V in OBJ;
}

This method of using the keyword in also has some restrictions. For example, you can only search for strings
The group element can be any value. In addition, arraytoobject () also has some overhead, which makes it
It is not suitable for search sets with frequent changes. Finally, (I think you may have noticed) use the object
When searching, the data cannot be accurately located, and the array can point to the subscript of the result.

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.