Next, object-oriented JavaScript programming

Source: Internet
Author: User

Keywords: Javascript OOPObject-orientedJScriptPrototype Prototype

Abstract:

In the original "Object-OrientedJavascriptProgramming, the author proposed throughJavaScript (To be exact, the above isMicrosoftOfJScript)To achieveOOPIn the original article, due to the limitations of the author's knowledge, there are some unreasonable ideas. Thanks to some comments provided by some netizens, the author corrected some ideas in the original article based on the actual work during this period..

 

Due to the limited level of personal knowledgeJavascriptIt only stopsMicrosoftOfJScriptAs for sumNetscapeThe difference between them is only beyond the scope I know. In the original article, the author puts forward the object-orientedJavascriptIs not intended to be sold out.ScriptI just think it will be used more or less in the development process, so I will give some feasible suggestions from my personal perspective.

 

ForJavascriptThe concepts of implementation, encapsulation, inheritance, overloading, and events are proposed. Due to the deviation of personal understanding, there are many inapplicable points in the original article, therefore, this article only provides some amendments to some personal opinions of the original article.

 

JavascriptSlaveOOPFrom the perspectiveOOPLanguage, more accurately, isObject-basedTherefore, the so-called class concept mentioned in the original article is only from the traditionalOOPLanguage, and the so-called class implementation should be a prototype implementation method, because in the whole implementation processPrototypeIs the most important embodiment.

 

Theoretically, allFunctionAllObjectSo the class creation can be completely based onObjectTo achieve this, the original article usesFunctionTo better implement some functions, we will implement, encapsulate, inherit, reload the event5Concepts.

1..

JavascriptOfFunctionIs a first-class citizen (HaxPrimitive), so useFunctionThe best way to achieve this is to use the following two sectionsCodeTo achieve this is determined based on the habits of personal programming, and some implementation deviations will be described in detail below.

 

Code1

Function myobject (sname ){

This. Name = sname;

This. MessageBox = function (){

Alert ("Name"+ This. Name );

}

This. changename = changename;

Function changename (){

This. Name ="Change"+ This. Name;

}

}

 

 Code2

 

Function myobject (sname ){

This. Name = sname;

}

Myobject. Prototype. MessageBox = function (){

Alert ("Name"+ This. Name );

}

Myobject. Prototype. changename = function (){

This. Name ="Change"+ This. Name;

}

 

There is no difference in the use of standard class implementation structures and prototype implementation methods (C ++,SmalltalkIn that language), we should adopt the first scheme, but for me personally, I suggest using the second scheme. After all, in the development process, such compiling method andJavascriptThe writing method is relatively close, basically based onFunction.

 

2. Encapsulation

Since the object concept is introduced, encapsulation must be taken into account,C ++Such languages are proposed.Private, protected, publicInJavascript, No correspondingProtectedBut inPrivateAndPublicIt can achieve implicit implementation. In addition, if you need to use a large number of private variables, it is more appropriate to use the solution in the implementation method, as shown in the following code.

 

Function myobject (sname ){

VaR mvar = 1;

This. Name = sname;

This. MessageBox = function (){

Alert ("Name"+ This. Name );

Mvar = 2;

}

This. changename = changename;

Function changename (){

This. Name ="Change"+ This. Name;

}

This. getvar = function (){

Return mvar;

}

}

 

MvarIs a private variable,NameIs a common variable, inMyobjectInternal functions can be accessedMvarVariable, andNameYou can useThis. NameIn any way, for internal function processing,ChangenameIt cannot be accessed directly, but it can be accessed throughObject. changename ()Access, these concepts inHaxThe comments described by several netizens are more detailed..

 

In short,JavascriptProvidesPrivateAndPublicBut does not provide explicit declaration. The functions and variables defined in class functions (Let me call it this way) are both private variables.This. methodnameOrThis. varnameAll definedPublicImplementedObject. Prototype. NameImplementation is alsoPublic,Private functions in class functions can access those private variables and functions.Object. Prototype. NameI have not done this before. If anyone has done this, please let me know.

 

InVbsMentioned inClassThe following code can fully reflect the encapsulation style.

Class myclass

Private vloginid

Public username

Public property get loginid

Loginid = vloginid

End propertyp

Public property let loginid (vvalue)

Vloginid = vvalue

End Property

End Class

 

InJavascriptThere is no explicit attribute concept.VbsThe encapsulation is indeed clean,Javascript

Does not have such a concept, but can use andJavaSimilar design methods, suchGet_propertyname, set_propertynameIn this way. I personally suggest using functions. If a parameter is includedSetOperation. If no parameter is included, it can be consideredGetOperation. In simple terms, the following code style is used.

Object. Prototype. Username = Function(Vvalue ){

If (vvalue ){

// Todo get

}

Else {

Return value;

}

}

The above is just my personal point of view.

3. Inheritance

In the original article, we mentioned that you can implement inheritance by setting the prototype.Subobject. Prototype = new baseobjectIn this way, the corresponding constructor is used in the original article.

This. base = parentclass;

This. Base ();

 

This method is actually completed by calling the constructor of the parent class.Prototype (Prototype)After settingSubobjectThe instantiated object can access all methods of the parent class. In the actual development process, the following problems are encountered. There is no difference between solution 1 and solution 2, but the following code is a bit strange.

Function son (sname ){

This. base = myobject;

This. Base (sname );

}

 

Son. Prototype. MessageBox = function (){

// This. Base. MessageBox ();

Alert ("Subclass call");

}

Son. Prototype. Hi = function (){

Alert ("KK ");

}

VaR o = new son ("hello ");

O. MessageBox ();

 

The final execution result is the aboveMyobject. MessageBoxMethod,Son. Prototype. MessageBoxThis function is not executed, and it is unclear whether it is my code or not. In terms of inheritance, I found thatThis. method = functionnameAndObject. Prototype. methodnameThe implementation does not seem completely the same. If anyone understands this, please let me know.

 

Not used in the code just nowPrototypeThe inheritance can be completed. The method used here should be the initialization of the constructor. ThereforeObject. MessageBoxAnd so on.Subobject. Prototype = baseobject, ThenBaseobject. Prototype. methodnameSome methods cannot be implemented.

 

4. Overload

In the original article, I mentionedObject. Prototype. methodnameBut at the same time, the question is how to call the method of the parent class.This. base = myobject, this. Base ()In this way, only some methods of constructor implementation can be implemented, that is, some methods or attributes defined by the parent class in the function body, through the prototypePrototypeImplementation cannot be achieved.Subobject. Prototype = new baseobjectIn that way, there will also be some problems mentioned above.

InJScript 5.5The above version has oneCallFunction, through which we can fully implement the method call for the parent class, just likeJavaInsideSuperTo achieve overload. If the reader's client system isIE6OrWinmeIs alreadyJscript5.5For the above versionXPOr2003I don't have to say much,JScriptIf the engine version is relatively low, we recommend that you download the higher version.

Baseobject

-------------------

Function baseobject (){

This. MSG = NULL

}

Baseobject. prototyp. Message (MSG ){

This. MSG = MSG;

Alert (this. msg );

This. MSG = "change" + this. MSG;

}

 

Subobject

Function subobject (){

 Baseobject. Call (this );

}

Subobject. Prototype = new baseobject;

Subobject. Prototype. Message = function (MSG ){

Baseobject. Prototype. Message. Call (this, MSG );

Alert (this. msg );

}

 

 Call Code

VaR v = new subobject ();

V. Message ("hello ");

 

The method of the parent class isCallCall,Call (this, argS)Indicates that the current instance is called.SubobjectMedium,Baseobject. Call (this)Call the method of the parent class.MessageIn order to maintain the original functionsMessageMethod, and then write your own implementation code.

 

From the code, we can see thatBaseobject. Prototype. methodname. Call (this, argS)This method is called becauseCallFunction, so it must be supported by a later version.

 

I have discussedJScriptAs for the implementation of other engines suchNetscapeOrFlash script, You can use_ PROTO __This will return the prototype of the parent class, so the call is much simpler,This. _ PROTO __EquivalentJavaInsideSuperCan be called directly here.

 

In earlier versionsJScriptI don't know if the engine can passInstanceofOr other functions can be implemented together, and we hope you can discuss them together.

 

5. Event

OriginallyOOPIn programming, I should not discuss such a problem, but in actual applications, it may need to use the form of similar events. Therefore, in the original article, it basically uses a similarC ++But only a common variable method is used for definition.

 

If the class itself isDomBound,HtmlAvailableFireeventFunction to trigger some events, but these should already belongDHTMLSomething discussed.

 

JavascriptIn itself, there is no such thing as object-oriented in the true sense. The original text and the content mentioned in this article are only some logical implementations in the actual development work. It is indeed not suitable for a large number of use within the browser.OOPButJScript LibraryFor developers, object-oriented can indeed provide a lot of benefits. The purpose of writing this article isJScript LibraryDevelopers can help, at least as a reference.

 

Because of its limited level, there may be some deviations in some understanding, and I hope someone can point it out to me.

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.