Object-oriented JavaScript programming

Source: Internet
Author: User
Tags eval functions implement inheritance reference return string tostring
Javascript| Programming | objects

Object-oriented JavaScript programming should not be unfamiliar to people who have done Web applications, initially to do some simple form validation, basically playing with some technical things. IE 4.0 introduced DHTML and, in order to combat Netscape's JavaScript, presented its own scripting language JScript, which, in addition to following the EMAC standard and adding a lot of extensions, is one of the following OOP programming to be mentioned, for the sake of life and concept, The JavaScript I mentioned below is JScript implemented by Microsoft Internet Explorer more than 4.0, and I haven't done too many programs for Netscape, so some of the differences can be seen.


Javascript


JavaScript is not a support-oriented language, not a development platform, but JavaScript provides a very powerful prototype-oriented object-oriented invocation feature that you can use in places you need. So, how do you use objects? This article, as far as possible from the JavaScript object-oriented implementation principle, analysis of its work model. After you understand these models, you can write some implementation code in your own script library and call it elsewhere.

JavaScript syntax and C + + is very close, but in the class implementation does not use the keyword class, the implementation of inheritance does not use the traditional public or implement, etc. so-called keyword to mark the implementation of the class. In this case, there might be people asking how to write JavaScript class and how to implement inheritance. I began to be baffled, and then looked at MSDN, only to know that the use of prototype to achieve, including inheritance and overloading, can also be a reality by this keyword.

The functions of JavaScript are strange, each of which is optional by default, that is, parameters can be optional, function A (VAR1,VAR2,VAR3), in the process of invocation a (), a (value1), A (value1,value2) And so on are all correct, at least even if the compilation part can pass completely, as for others, it is only related to the implementation logic of the function.

The following JS for the implementation of the class, inheritance, overload detailed description of its implementation.

1. Realize

The implementation of the JS class is directly implemented through the function, each function can be directly regarded as class, the following code

function ClassTest1 () {

...//implement code

}

var a=new ClassTest1

function ClassTest2 (var1) {

...//implement code

}

var b=new classtest ("value")

For the properties of a class, you can implement it in two ways

1) this. " <property or method to implement the function directly in the class declaration function, such as this. add=new function (Strusername,strpassword) is called in such a way that it is written in a class function.

2) through Classfunction.prototype. [Functionname]=function (Var1,var2 ...) {//todo} completes the call in such a manner.

The two approaches are consistent from the goal, and according to my personal point of view, the difference is only in the way of implementation, Created by This.propertyname, JScript automatically creates the entry of the property or method, but it is more flexible from the point of view of the program or using the prototype keyword.

In addition JavaScript can also and we C + + that kind of nested declaration method to declare, C + + implementation of the method is as follows

Public Class classname:parentclass{

Public DataType functionname () {

}

Public Class classname{

Public DataType functionname () {

}

}

}

In JavaScript, of course, there is no class such a keyword, so the implementation is a bit dramatic, but still for 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 () {

}

As the code above illustrates the implementation of the properties and methods in JavaScript classes, there is a bit of confusion, the whole class is public, no keyword private and so can control whether some methods are hidden, then in our code implementation of the specification, I think some foreign programmers use _functionname as a function of the method to distinguish, but in the call process can actually be called.

Implementation of the properties and methods, the rest is the implementation of the event, I looked up a lot of information, including the entire MSDN reference to JScript, did not see a good model on the event implementation, and later referred to some of the site to write HTA (HTML Component, I will be able to write some related articles in a short time, with the help of the more distorted (I personally think) method can be roughly implemented based on event-driven features. The general idea is this:

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

2. In the code that needs to trigger the event, determine if the event property is a function, if it is a function, execute the function code directly, and if it is a string, execute the string function through eval (str).

3. Registers an event function with an instance of a class.

In order to simply explain the idea, using a simple example like timer to describe the content mentioned above, if only for the simple implementation of timer functions, JavaScript setinterval function can meet all the requirements, The following code is used to illustrate how a timer works.

Class for Timer
function Timer (iinterval) {
If not set the timer interval, then Defalut set to 500ms
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 work code is implemented on TimerCallback (), event triggers are implemented as attributes, and in the application instance, the code provides three ways to invoke the event, but in the callback of the event, I have not thought how to take parameters, Only in their respective implementation of access to their own needs of the attributes to achieve the full requirements.

2. Inherited.

Just used a large amount of text to introduce how to achieve a variety of javascript implementation, that is, a logical completion of the implementation of a package class, in a sense, class implementation is the most used part of real scripting programming, but if only to complete the functions as above, Using VBScript to write is much clearer, after all, VBScript provides the class keyword, while providing the two keywords public and private, which can be used to clearly separate common and proprietary objects, and for the implementation of events, can also use similar JavaScript implementation of the idea, but for the function of reference need to use getref this function, the specific use can refer to scripting Reference,msdn inside also have detailed introduction, And JavaScript is strong as follows, although the specific things may not be much.

As mentioned above, we have completed a basic class implementation timer, now to do is rewrite the class, we simply want to add a method in this class, provide the current system time, the method name is Getsystemdate, obviously if all rewritten, That would have lost the meaning of what I have said here. First 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 implements the Newtimer class, which inherits from the timer, JavaScript does not use ":" or Java-like keywords, just through the newclassname.prototype=new BaseClass This method to complete, at the same time Newtimer implemented the Getsystemdate method, in Newtimer initialization function, I used This.base=timer, is to refer to the implementation of the parent class, However, in the invocation of other implementation functions for the parent class, until now I have not found a certain method, whether through the This.base.start () to invoke or other, if there is more clear, trouble to tell me, in addition to Netscape's site, I found that there is a special "__ The proto__ attribute seems to be a direct reference to the parent class, but I haven't tried it, nor have I seen support for __proto__ in MSDN.

3. Overload

Perhaps this is the more complex OOP programming, in the JavaScript implementation of a bit helpless, that is, through the prototype way to do, but because I do not know how to invoke the implementation of the parent class, then in the overload can only rewrite all the implementation, The other is to instantiate a parent class in the implementation and then return what is needed by calling it.

All objects in JavaScript are inherited from object, and object provides the method of ToString (), which means that if the procedure such as alert (objinstance) is invoked, it actually invokes alert ( Objinstance.tostring ()) method, if not written implementation, object default toString () is "object" like this, in many places need to overload this function, such as timer, if we want to Var Ins=new Timer (5); alert (INS) call gets the value of interval 5, then you need to rewrite the ToString () method.

Timer.prototype.tostring=function () {return this. Interval};

After the above code is implemented, alert (INS) gets 5.

Excerpt from: http://www.zahui.com/html/7/14421.htm



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.