JavaScript Object-oriented support (2)

Source: Internet
Author: User
Tags array constructor interface key words reflection client
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)
================================================================================

2). The realization of reflection mechanism in JavaScript
------
In JavaScript, pass for ... In syntax to implement the reflection mechanism. But the JavaScript doesn't
Distinguish between "properties" and "methods", and "events" explicitly. Therefore, the type of the attribute is examined in JS
is a problem. The following code is a simple example for.. Use in and attribute recognition:
//---------------------------------------------------------
In JavaScript for.. Use and attribute recognition in
//---------------------------------------------------------
var _r_event = _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 '
: ' Property ';
}

var objectarr = [' Window ', ' obj2 '];

for (var i=0; i<objectarr.length; i++) {
Document.writeln (' <p>for ', objectarr[i], '

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> ');
}

One fact that is often overlooked by developers is that JavaScript itself is not an event system. Usually the onclick events we use in JavaScript are actually provided by the DOM model of IE. From a more kernel point of view: IE through the COM interface properties of the publication of a set of event interface to the DOM.

There are two reasons why the "one attribute is not an event" is not well recognized in JS:

-Only methods, properties, and events in the COM interface are published by a set of Get/set methods.
-In JavaScript, there is no independent "event" mechanism in itself.

So we see an event identification method that detects whether an attribute name starts with an ' on ' string (the Qomo convention begins with ' on '). Next, because the events in a DOM object can not specify a handler function, the event handle is a null value (Qomo uses the same convention), and in other cases the user may define an event with a value of undefined like obj2. Thus the decision condition of "event" is processed into a complex expression:
("The property starts with On/on" && ("value is null/undefined" | | "Type is a function")

In addition, from the above code to run the results look. Use for ... for DOM objects. In, it is not possible to enumerate the object methods.

Finally, the point is stated. In fact, in many language implementations, "events" are not "object-oriented" language features, but are provided by a specific programming model. For example, the event-driven mechanism in Delphi is provided by the window message mechanism in the WIN32 operating system, or by the user code to invoke the event handler function in the Component/class.

"Event" is a mechanism/problem of how to drive a programming model, not a problem with the language itself. However, with PME (property/method/event) as the framework of OOP concept, has been deeply rooted, so when the programming language or system to show these features, no one is concerned about "who is the implementation of the event."


3. This and with the use of the keyword
------
In a JavaScript object system, the This keyword is used in two places:

-Refers to a newly created object instance in a constructor function
-Refers to an object instance that calls the method when the object's method is called

If a function is called as a normal function (rather than an object method), the This keyword in the function points to the Window object. Similarly, if this keyword is not in any function, he also points to the Window object.

Because there is no explicit distinction between functions and methods in JavaScript. So some of the code looks strange:
//---------------------------------------------------------
Several possible invocation forms of a function
//---------------------------------------------------------
function foo () {
The following this refers to an object instance that calls the 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 refers to the New keyword creation instance
THIS.name = name;
This.foo = foo;
}

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

Test 1: As a function call
Foo ();

Test 2: Call As Object method
Obj1.foo ();
Obj2.foo ();

Test 3: Call the function as a "specified object" method
Foo.call (OBJ1);
Foo.apply (OBJ2);

In the above code, OBJ1/OBJ2 's Call to Foo () is a very common calling method. -that is, the method that specifies a function as an object on the constructor.

The call () and apply () in test 3 are very special.

In this Test, Foo () is still invoked as a normal function, except that the language characteristics of JavaScript allow for a reference to the This keyword that appears in the context of Foo () by passing in an object instance when call ()/apply (). Note that at this point Foo () is still a normal function call, not an object method call.

This "indicates the object instance that called this method" is somewhat similar, with () syntax is also used to qualify "Use object instances by default in a piece of code". If you do not use the WITH () syntax, the code will be affected by the more outer with () statement, and if there is no more outer with (), then the "Default object instance" for this code will be window.

However, it is important to note that this and the WITH keyword are not mutually affected. As in the following code:
//---------------------------------------------------------
Test: This and the WITH keyword are not mutually affected
//---------------------------------------------------------
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 can't expect such code to have the Obj2.value property set to 8 after the call ends. The result of these lines of code is that the Window object has one more Value property and a value of 8.

With (obj) {...} This syntax can only restrict the reading of the existing attributes of obj, but not the active declaration of it. Once the object in the with () does not have a specified property, or the With () qualifies a data that is not an object, the result creates an exception.


4). Operation using in keyword
------
In addition to using for.. In to reflect the member information of an object, JavaScript also allows you to use the In keyword directly to detect whether an object has an attribute of the specified name.

The reason that the in keyword is often mentioned is not its ability to detect the existence of a property, so in the early code, many might prefer to use the "if (!obj.propname) {}" method to detect whether the propname is a valid property. Most of the time, detection effectiveness is more practical than detecting the existence of this attribute. So in this case, in is just an optional, official program.

The important application of the IN keyword is high speed string retrieval. Especially if you only need to determine if the string exists. For example, 100,000 strings, if stored in an array, then the retrieval efficiency will be extremely poor.
//---------------------------------------------------------
Use objects to retrieve
//---------------------------------------------------------
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;
}

There are some limitations to this method of using keyword in. For example, you can find only strings, and an array element may be any value. In addition, Arraytoobject () also has some overhead, which makes it unsuitable for frequently changing lookup sets. Finally, (I think you might have noticed) when you use an object to find it, you can't exactly navigate to the lookup data, 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.