Object-oriented JavaScript programming

Source: Internet
Author: User
Javascript For Web ProgramPeople should not be unfamiliar. They were initially used for some simple Form Verification is basically playing with something tricky. IE 4.0 Introduced DHTML To combat Netscape Of Javascript, Proposed their own scripting language JScript In addition EMAC In addition to the standard, many extensions are added. OOP Programming is one of them. For the sake of life and concept, what I mentioned below Javascript All Microsoft Iot Explorer 4.0 The above implementation JScript, For Netscape , I have not done too many programs, so some differences can be seen.


JavascriptIt is not an object-oriented language, but not a development platform,JavascriptProvides a very powerfulPrototypeYou can use them wherever you need them. Therefore,How to use objects? This article triesJavascriptThe working model of object-oriented implementation is clearly parsed. After learning about these models, you can write some implementations in your script library.CodeAnd then call it elsewhere.

 

JavascriptSyntax andC ++Very close, but no keywords are used in class implementationClass,The traditionalPublicOrImplementAnd so on. In this case, someone may ask how to writeJavascriptOfClass, How to implement inheritance. I was puzzled at the beginning.Msdn,Only then can we know thatPrototypeThis keyword can be used for implementation, including inheritance and overloading.

 

JavascriptEvery function is implemented by default.Optional, That is, the parameters are optional,Function A (var1, var2, var3 ),During the call ProcessA (), A (value1), A (value1, value2)And so on are all correct, at least even if the Compilation part can be fully passed, as for others, it is only related to the Implementation logic of the function.

BelowJSDescribes how to implement, inherit, and overload classes in detail.

1. Implementation

JSClass implementation is directly implemented through functions, each function can be directly seenClass, The following code

Function classtest1 (){

... // Implement code

}

VaR A = new classtest1

Function classtest2 (var1 ){

... // Implement code

}

VaR B = new classtest ("value ")

Class attributes can be implemented in two ways

1)This. "<property or method"The implementation of the function is provided directly in the class declaration function, as shown in figureThis. Add = new function (strusername, strpassword)This method is called inClass Function.

2) PassClassfunction. Prototype. [functionname] = function (var1, var2....) {// todo}This method is used to complete the call.

The two methods are consistent in terms of goals. From my personal point of view, the difference is thatThis. propertynameTo create,JScriptAutomatically createdPropertyOrMethodBut from the perspective of the program, we still usePrototypeKeyword implementation is more flexible.

In additionJavascriptYou can also contact usC ++In the nested declaration method to declare, C ++The implementation method is as follows:

Public class classname: parentclass {

Public datatype functionname (){

 

}

Public class classname {

Public datatype functionname (){

}

}

}

InJavascriptOf course, this does not exist.ClassThis is a keyword.,So the implementation is a little dramatic, but it is still a very clever implementation.

Function classname (){

// Property implement

This. Username = "blue ";

// Method Implement

This. Add = new function (){

 

}

// Sub class implement

Function subclassname (){

This. propertyname = "hi"

}

// Sub class Method Implement

Subclassname. Prototype. Change = function {

 

}

}

// Main class Method Implement

Classname. Prototype. Delete = function (){

 

}

The above code roughly demonstratesJavascriptThe implementation of attributes and methods in the class is also a bit confusing, the wholeClassBothPublic, No keywordsPrivateAnd so on, we can control whether some methods are hidden. In the code implementation specification, I think some programmers abroad use_ FunctionnameIn this way, the function life methods are differentiated, but they can be called in the call process.

Implements attributes and methods, and the rest isEventI found a lot of information, including the entireMsdnAboutJScriptI didn't see a good model about event implementation, but later I wrote it by referring to some sites.HTA (HTML component,I will write some relatedArticle), With the help of a relatively distorted (I personally think) method, you can roughly implement the event-driven function. The general idea is as follows:

1).Define all events as attributes, as long as a simple declaration

2).In the code that needs to trigger the event, determine whether the event attribute is a function. If it is a function, directly execute the function code. If it is a string, then execute the string function throughEval (STR).

3 ).Register the event function in the instance of the class.

To briefly describe the above ideasTimerThis is a simple example to describe the content mentioned above.TimerFunctions,JavascriptMediumSetintervalThe function can meet all the requirements. The following code is only used to describeTimer.

// Class for Timer
Function timer (iinterval ){
// If not set the timer interval, then defalut set to 500 ms
This. interval = iinterval | 500;
This. _ handleinterval;
This. timerevent = NULL
Function start (){
If (this. Interval! = 0 ){
This. _ handleinterval = setinterval ("timercallback ()", this. interval );
}
}
Function start (){
Clearinterval (this. _ handleinterval );
}
Function timercallback (){
If (typeof this. timerevent = "function "){
This. timerevent ();
}
Else if (this. timerevent! = NULL & this. timerevent. length> 0 ){
Eval (this. timerevent );
}
}
}
// Code for instance
VaR T = new timer (3 );

//------------------------------------//

// 1.
T. timerevent = function (){
// Todo
}

// 2.
T. timerevent = "alert (\" Hello \")";

// 3.

T. timerevent = ttimercall;

//----------------------------------//
T. Start ();
T. Stop ();

Function ttimercall (){

 

}

 

The actual working code is inTimercallback ()In the above implementation, event triggering is implemented as a property method. In the application instance, the Code provides three methods to call events, but in the Event Callback, I have not yet thought of how to include parameters. Only in their respective implementations can they access the required attributes to achieve all the requirements.

 

2. Inheritance.

I just used a large article to explain how to implement it.JavascriptThe various implementations, that is, a logical EncapsulationClassIn a sense,ClassIs the most used part of real script programming, but if you only want to complete the above functions, useVBScriptTo write more clearly, after allVBScriptProvidedClassKeyword.PublicAndPrivateThese two keywords can clearly separate public and private objects. For event implementation, you can also use a similarJavascriptThe implementation idea is to useGetrefFor specific usage of this function, referScripting reference, msdnThere are also detailed descriptions, andJavascriptThe power is as follows, although there may not be many specific things.

As mentioned above, we have completed a basic class implementationTimerNow we need to re-compile this class. We just want to add a method to this class to provide the current system time. The method name isGetsystemdate,Obviously, if you rewrite all of them, it will lose the meaning of what I have mentioned here. Let's take a look at the following implementation.

Function newtimer (iinterval ){

// Call Super

This. base = timer;

This. Base(Iinterval );

}

Newtimer. Prototype = new timer;

Newtimer. Prototype. getsystemdate = function (){

VaR dt = new date ();

Return DT. getyear () + "-" + dt. getmonth () + "-" + dt. getday ();

}

The above code implementsNewtimerClass, fromTimerInheritance,JavascriptNot used":"OrJavaOfPublicA keyword similar to this isNewclassname. Prototype = new baseclassIn this wayNewtimerImplementedGetsystemdateInNewtimerIn the initialization function, I usedThis. base = TimerTo reference the implementation of the parent class. However, I have not found a definite method for calling other implementation functions of the parent class.This. Base. Start ()In this way, the call is another one. If anyone knows clearly, please let me know.NetscapeOn the site, I found a special"_ PROTO __"It seems that the attribute of is a direct reference to the parent class, but I have not tried it.MsdnNo_ PROTO __.

3. Heavy Load

Maybe this isOOPProgramming is complicated.JavascriptIs a little helpless, that is, throughPrototypeBut because I don't know how to call the implementation function of the parent class, I can only re-compile all the implementations in the overload, the other is to instantiate a parent class in the implementation and then call it to return what is needed.

JavascriptAll objects areObjectInherited,ObjectProvidedTostring ()Method, that is, if you callAlert (objinstance)This process is actually calledAlert (objinstance. tostring ())If no implementation is written,ObjectDefaultTostring ()All"Object object"In this way, this function needs to be reloaded in many places, suchTimer,If we wantVaR ins = new timer (5); alert (INS)The call result isIntervalValue5, You need to re-compileTostring ()Method

Timer. Prototype. tostring = function () {return this. interval };

After the above Code is implementedAlert (INS)The result is:5.

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.