Inheritance of objects in javascript [Post 〕

Source: Internet
Author: User

1. apply and call functions of javascript
Prototype. js uses a large number of apply and call functions, which may cause misunderstanding if you do not pay attention to them.
Official explanation: apply a method of an object and replace the current object with another object.
The difference between apply and call is that the second parameter is different. Apply Is an array or arguments object. Call is of any type separated by commas.

Apply: the most confusing part of the call method is the characteristics of apply and call. But it is best not to abuse it.
The object that can call the function. In the following example, the this keyword is used in the function. In this case, this represents the first parameter of the apply and call functions.

<Script src = "prototype1.3.1.js"> </script>
<Input type = "text" id = "myText" value = "input text">
<Script>
Function Obj (){
This. value = "object! ";
}
Var value = "global variable ";
Function Fun1 (){
Alert (this. value );
}
Window. Fun1 ();
Fun1.apply (window );
Fun1.apply ($ ('mytext '));
Fun1.apply (new Obj ());
</Script>

2. About closures
Prototype. js uses javascript closure features in Class. create and bind. However, prototype. js is rarely used for powerful closure features. You can refer to the article I translated to learn about closures.
3. Two methods that I dislike
(1)
Var Class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}
I hate writing javascript in other languages. Using this method to construct a custom class is not as convenient as it reduces the number of lines of code. It is hard to understand and define an initialize method.
In fact, it is a little far-fetched to hate this article, but it is a little too much to modify the Object's prototype Object.
(2) Object. prototype. extend
First, however, the Ambiguity Caused by getting an extend name will make people familiar with java. You cannot modify the prototype of an Object. I don't know how the author considers it. When your for in loop object is, the trouble is coming. Someone may ask you why. In my project, both DWR and prototype. js are used. The javascript objects returned by dwr have multiple exetend attributes and must be specially processed.
I used to compare the inheritance implementations in dojo and prototype. js. Now I understand the truth. For javascript, a language without static type check and with loose syntax, if you choose a js class library, you must also adapt to the style of writing javascript by the author. The author of prototype. js is very enthusiastic about the use of extend. If it is not an attribute copy function, it is good to read more prototype. js code.
4. Function binding
The Class Library provides two methods: Function. prototype. bind Function. prototype. bindAsEventListener. First, we will explain one of these two methods in terms of concept.
Any function can call these two methods. The parameter is a javascript object or an element object on the webpage, And the return type is a function object.
Originally, I was a function. The return or function. What are the differences between the two functions. The key to the implementation code is the code of the apply \ call function. In fact, it only converts the object of the method call.

<Script src = "prototype1.3.1.js"> </script>
<Input type = checkbox id = myChk name = "asf" value = 1> Test
<Script>
Var CheckboxWatcher = Class. create ();
CheckboxWatcher. prototype = {
Initialize: function (chkBox, message ){
This. chkBox = $ (chkBox );
This. message = message;
This. chkBox. onclick = this. showMessage. bindAsEventListener (this );
},
ShowMessage: function (evt ){
Alert (this. message + '(' + evt. type + ')');
}
};
New CheckboxWatcher ('mychk', 'message !!!! ');
// $ ('Mychk'). onclick = function (){};
</Script>
This is an example of https://compdoc2cn.dev.java.net/, personal feeling is not interesting, but let me bind, bindAsEventListener some dislike. (Javascript is like this. We know the syntax clearly, but the code written is quite different)
See the following code:

<Script src = "prototype1.3.1.js"> </script>
<Input type = checkbox id = myChk name = "chk" value = 1> Test
<Script>
Function Class (){
This. name = "class ";
}
Class. prototype. getName = function (){
Alert (this. name );
}
Var obj = new Class ();
// $ ('Mychk'). onclick = obj. getName;
$ ('Mychk'). onclick = obj. getName. bind (obj );
// $ ('Mychk'). onclick = obj. getName. bind ($ ('mychk '));
</Script>

From the code above, we can see that bind/bindAsEventListener only wraps the apply/call method and changes the call object of the method. For example, you can convert the obj. getName method to any object call and trigger the method for the form element. (Only the parameters of the returned function are different between bind and bindAsEventListener)
These two methods can also be used in method reuse between objects to implement the concept similar to the inherited method. The following code is actually boring.

<Script src = "prototype1.3.1.js"> </script>
<Script>
Function Class1 (name ){
This. name = name;
}
Class1.prototype. getName = function (){
Alert (this. name );
}
Function Class2 (name ){
This. name = name;
This. getName = Class1.prototype. getName. bind (this );
}
Var obj1 = new Class2 ("yql ");
Obj1.getName ();
Var obj2 = new Object ();
Obj2.name = "zkj ";
Obj2.fun = Class1.prototype. getName. bind (obj2 );
Obj2.fun ();
</Script>

I have never read the extended project code of prototype. js or the best practices of bind. But you should never understand bind/bindAsEventListener from the meaning of the binding, which may make you more confused. Understand the essence from apply/call. Apply a method of an object and replace the current object with another object.

5. event registration

<Script src = "prototype1.3.1.js"> </script>
<Input type = checkbox id = myChk name = "chk" value = 1> Test
<Script>
Event. observe (myChk, 'click', showMessage, false );
// $ ('Mychk'). onclick = showMessage;
// $ ('Mychk'). onclick = showMessage. bind ();
$ ('Mychk'). onclick = showMessage. bind ($ ('mychk '));
Function showMessage (){
Alert (this. value );
}
</Script>

Run the above Code to understand the differences between Event. observe and bind/bindAsEventListener:
(1) Obviously, Event. observe has limits. It can only process simple functions, and functions cannot contain such items.
(2) addEventListener/attachEvent is used in Event. observe. You can add multiple functions to a trigger event (window. onload ). Bind is overwrite.

6. Best practices for event monitoring
Obviously, the event registration method provided by prototype. js is not perfect. Let's take a look at the time registration of dojo (Chinese version). It is more complicated. It is estimated that many people like me are holding a wait-and-see attitude towards dojo for the time being.
If you have read the previous introduction to closures, you may have seen the following code.
Before reading the following code, I want to express a point of view. Any element in a webpage, the browser will create an object for you (SEE ). (I think) the difference between these objects and your javascript objects is that they have event listening and will respond to mouse and keyboard events. If you use the following code, the event listening code is well converted to your javascript code.

Function associateObjWithEvent (obj, methodName ){
Return (function (e ){
E = e | window. event;
Return obj [methodName] (e, this );
});
}
Function DhtmlObject (elementId ){
Var el = getElementWithId (elementId );
If (el ){
El. onclick = associateObjWithEvent (this, "doOnClick ");
El. onmouseover = associateObjWithEvent (this, "doMouseOver ");
El. onmouseout = associateObjWithEvent (this, "doMouseOut ");
}
}
DhtmlObject. prototype. doOnClick = function (event, element ){
... // DoOnClick method body.
}
DhtmlObject. prototype. doMouseOver = function (event, element ){
... // DoMouseOver method body.
}
DhtmlObject. prototype. doMouseOut = function (event, element ){
... // DoMouseOut method body.
}

Some time I want to use the above idea to implement a code for dragging a webpage floating box (in fact there are already a lot of code), to be continued ........

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.