JavaScript Object-oriented support (5)

Source: Internet
Author: User
Tags date array constructor key words net reference requires window
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. Another property that requires user maintenance: constructor
------
Looking back at the previous section, we have mentioned:
-(If the inheritance model is implemented properly,) the constructor property of the object instance points to the constructor
-Obj.constructor.prototype point to the object's prototype
-Through the Object.constructor property, you can detect whether Obj2 and Obj1 are instances of the same type

As with the prototype chain to maintain the prototype property through user code, the constructor property of the instance constructor
User code maintenance is also required.

For JavaScript's built-in objects, the constructor attribute points to a built-in constructor function. Such as:
//---------------------------------------------------------
//Built-in object instance's constructor properties
---------------------------------------------------------
var _object_types = {
  ' function '  : Function,
  ' Boolean '   : Boolean,
  ' regexp '    : regexp,
//' math '     : Math,
//' Debug '    : Debug,
//' image '    : image;
' undef '    : Undefined,
//' dom '      : Undefined,
//' ActiveX '  : Undefined,
  ' VBArray '   : VBArray,
  ' array '     : Array,
& nbsp ' String '    : String,
  ' Date '      : date,
  ' ERROR '      : Error,
  ' enumerator ': Enumerator,
  ' number '    : number,
  ' object '    : Object
}

function Objecttypes (obj) {
if (typeof obj!== ' object ') return typeof obj;
if (obj = = null) return ' null ';

for (var i in _object_types) {
if (Obj.constructor===_object_types[i]) return i;
}
Return ' Unknow ';
}

Test data and related code
function MyObject () {
}
function MyObject2 () {
}
Myobject2.prototype = new MyObject ();

Window.execscript (' +
' Function Createvbarray () ' +
' Dim A (2, 2) ' +
' Createvbarray = a ' +
' End Function ', ' VBScript ');

Document.writeln (' <div id=dom style= ' display:none ' >dom< ', '/div> ');

Test code
var ax = new ActiveXObject ("Microsoft.XMLHTTP");
var dom = document.getElementById (' dom ');
var vba = new VBArray (Createvbarray ());
var obj = new MyObject ();
var obj2 = new MyObject2 ();

Document.writeln (Objecttypes (VBA), ' <br> ');
Document.writeln (objecttypes (AX), ' <br> ');
Document.writeln (Objecttypes (obj), ' <br> ');
Document.writeln (Objecttypes (obj2), ' <br> ');
Document.writeln (Objecttypes (DOM), ' <br> ');

In this example, we find that the constructor attribute is not fully implemented. For DOM objects, ActiveX objects
This attribute is not returned correctly.

Rather, DOM (including image) objects and ActiveX objects are not in the standard JavaScript object system,
So they may also have their own constructor attributes and have different interpretations of JavaScript. So
It is reasonable to not maintain their constructor properties in JavaScript.

Some other monomer objects (instead of constructors) do not have constructor properties, such as "Math" and "Debug",
' Global ' and ' RegExp object '. They are constructed within JavaScript and should not be exposed to the details of the constructs.

We also found that the constructor of instance obj points to function MyObject (). This means that JavaScript maintains a
The constructor attribute of the image. This is not the same as some people think.

Then again, we find that the instance of MyObject2 () Obj2 constructor still points to the function MyObject ().
Although this makes no sense, it is true. --What is this all about?

In fact, just the following code:
--------
function MyObject2 () {
}

Obj2 = new MyObject2 ();
Document.writeln (MyObject2.prototype.constructor = = = MyObject2);
--------
The constructed obj2.constructor will correctly point to the function MyObject2 (). In fact, we will also notice that this
Case, the constructor of the MyObject2 's prototype property also points to the function correctly. However, because JavaScript
Requires that the prototype object be specified to construct the prototype chain:
--------
function MyObject2 () {
}
Myobject2.prototype = new MyObject ();

Obj2 = new MyObject2 ();
--------
When you visit Obj2, you will get the constructor properties of the new prototype (that is, myobject2.prototype).
Therefore, it is clear that the properties of the stereotype affect the initial setting of the constructor of the object by the construction process.

As a complement to the problem-solving approach, JavaScript development specification says "need to remember to reset"
The constructor property ' requires the user to set the attribute himself.

So you'll see more canonical JavaScript code that requires this writing:
//---------------------------------------------------------
Maintaining canonical code for constructor properties
//---------------------------------------------------------
function MyObject2 () {
}
Myobject2.prototype = new MyObject ();
MyObject2.prototype.constructor = MyObject2;

Obj2 = new MyObject2 ();


A further way to solve the problem is to reset the value in function MyObject (). Of course, this will make
To perform a little less efficiently:
//---------------------------------------------------------
The second way to maintain constructor properties
//---------------------------------------------------------
function MyObject2 () {
This.constructor = Arguments.callee;
Or, this.constructor = MyObject2;

// ...
}
Myobject2.prototype = new MyObject ();

Obj2 = new MyObject2 ();


5). The problem of deconstruction
------
There is no destructor in JavaScript, but there is an "object destructor" problem. That is to say, although we do not
Know when an object is to be refactored, and it cannot intercept its destructor and process some transactions. However
In some rare cases, we encounter the question of "requiring an object to be immediately destructor".

The problem occurs most of the time on the handling of ActiveX object. Because we might be in JavaScript
Creates an ActiveX Object, and after some processing is done, we need to create another one. and
If the original object provider (Server) does not allow multiple instances to be created, then we need to be in the JavaScript
To ensure that previous instances have been released. Next, even if server allows multiple instances to be created,
Allow shared data between multiple instances (such as OS authorization, or resource, file locks), then we're in the new
The operation in the instance may cause problems.

Maybe someone doesn't understand what we're talking about, so I'll give you an example: If you create an Excel object,
Open file A, then we save it, and then close this instance. Then we create the Excel object and open the
The same file. Note that JavaScript may not have had time to deconstruct the previous object. --When we
If you want to save this file, you will find that you have failed. The following code example is the case:
//---------------------------------------------------------
The destructor problem in JavaScript (ActiveX object example)
//---------------------------------------------------------
<script>
var strsavelocation = ' File:///E:/1.xls '

function Createxls () {
var excel = new ActiveXObject ("Excel.Application");
var wk = Excel. Workbooks.Add ();
Wk. SaveAs (strsavelocation);
Wk. Saved = true;

Excel. Quit ();
}

function Writexls () {
var excel = new ActiveXObject ("Excel.Application");
var wk = Excel. Workbooks.Open (strsavelocation);
var sheet = wk. Worksheets (1);
Sheet. Cells (1, 1). Value = ' Test string ';
Wk. SaveAs (strsavelocation);
Wk. Saved = true;

Excel. Quit ();
}
</script>

<body>
<button > Create </button>
<button > Rewriting </button>
</body>

In this example, the local file operation does not cause an exception. --at most, there's just some memory.
Rubbish only. However, if strsavelocation is a remote URL, then local will save a
Credentials for file access permissions, and only one (remote) instance can be used to open the Excel document concurrently
Storage. Then if you repeatedly click the "Rewrite" button, there will be an exception.

-Note that this is a simplified code for an instance of operating a shared file in an SPS. Therefore, it is not
"Academic" boring discussion, and practical problems in engineering.

The way to solve this problem is very complicated. It involves two questions:
-Release of local voucher
-Release of an ActiveX object instance

Let's start with the "fail" problem of the object in JavaScript. To put it simply:
-An object is invalidated outside the context in which it is living.
-A global object is invalidated if it is not being used (referenced).

For example:
//---------------------------------------------------------
When JavaScript objects fail
//---------------------------------------------------------
function Testobject () {
var _obj1 = new Object ();
}

function TestObject2 () {
var _obj2 = new Object ();
return _obj2;
}

Example 1
Testobject ();

Example 2
TestObject2 ()

Example 3
var obj3 = TestObject2 ();
OBJ3 = null;

Example 4
var obj4 = TestObject2 ();
var arr = [Obj4];
OBJ3 = null;
arr = [];

In these four examples:
-"Example 1" constructs a _obj1 in the function Testobject (), but when the function exits,
It has left the context of the function, so the _obj1 is invalidated;
-In "Example 2", an object is also constructed in TestObject2 () _obj2 and is outgoing because
This object has a context environment (and a lifetime) outside of the function, however, because the function
The return value is not "held" by other variables, so the _obj2 is immediately invalidated;
-In "Example 3", the _obj2 of the TestObject2 () construct is held by an external variable obj3,
At this point, it is not until the "obj3=null" line of code takes effect that _obj2 the reference relationship
Disappear and fail.
-For the same reason as Example 3, the _obj2 in "Example 4" will be in the "arr=[]" line of code
Before it becomes ineffective.

However, the "expiration" of an object is not "released". Within the JavaScript runtime environment, no
There is any way to tell the user exactly when the object will be released. This relies on javascript
Memory recovery mechanism. --This strategy and. NET, the recycling mechanism is similar.

In the previous Excel action sample code, the owner of the object, which is "Excel." EXE "This process
Occurs only after "release of an ActiveX object instance". And the lock of the file, and the operation
The system's permission credentials are process-dependent. So if the object is only "fail" instead of "release",
Then other processes can cause problems when processing files and referencing the permissions credentials of the operating system.

Some people say this is a bug in JavaScript or COM mechanics. Not really, this is OS, ie
And JavaScript is a complex relationship that results, rather than an independent, problem.

Microsoft exposes a strategy to address this problem by actively invoking the memory recycle process.

A collectgarbage () process (usually referred to as a GC process) is provided in JScript (Microsoft).
The GC process is used to clean up the "failed object lost case" in current IE, which is the destructor of the calling object.

The code that invokes the GC procedure in the previous example is:
//---------------------------------------------------------
Standard invocation method for GC process when handling ActiveX object
//---------------------------------------------------------
function Writexls () {
(Slightly ...)

Excel. Quit ();
Excel = null;
SetTimeout (CollectGarbage, 1);
}

The first line of code calls Excel. Quit () method to cause the Excel process to abort and exit, when JavaScript
The Excel process does not actually abort because the environment holds an instance of an Excel object.

The second line of code makes Excel null to clear the object reference, causing the object to "fail". However because
object is still in the function context, so if you call the GC procedure directly, the object will still not be cleaned up.

The third line of code uses settimeout () to invoke the CollectGarbage function, with the interval set to ' 1 ' and only
is to make the GC process occur after the Writexls () function has been executed. This way the Excel object is satisfied with the "ability to be
GC Cleanup Two conditions: no referencing and leaving the context environment.

The use of GC processes is effective in JS environments that use ActiveX object. Some of the potential ActiveX
Object includes XML, VML, OWC (Office Web componet), Flash, and even vbarray included in JS.
From this point of view, Ajax architecture because of the adoption of XMLHTTP, and at the same time to meet the "do not switch pages"
attribute, and therefore actively invoke the GC process at the appropriate time, it is better to be more efficient with the UI experience.

In fact, even with the GC process, the Excel problem mentioned earlier will not be completely resolved. Because IE Also
The permission credentials are cached. The only way to make the page's permission credentials updated is to "switch to a new page".
So in fact, in the SPS project mentioned earlier, the method I used was not GC, but the following
Paragraph code:
//---------------------------------------------------------
Page switch code used when handling ActiveX object
//---------------------------------------------------------
function Writexls () {
(Slightly ...)

Excel. Quit ();
Excel = null;

The following code resolves a bug in IE call Excel, which is provided in MSDN:
SetTimeout (CollectGarbage, 1);
Because the trusted state of the Web page cannot be purged (or synchronized), it will cause methods such as SaveAs () to
The next call is invalid.
Location.reload ();
}

Finally, a supplementary note about GC: When IE forms are minimized, IE will actively call once
CollectGarbage () function. This allows the IE window to be minimized, memory footprint will be significantly improved.



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.