Home > Web Front-end > JS Tutorial > Inheritance of objects in javascript [repost]_javascript skills

Inheritance of objects in javascript [repost]_javascript skills

WBOY
Release: 2016-05-16 19:20:23
Original
903 people have browsed it
1. About the apply and call functions of javascript
A large number of apply and call functions are used in prototype.js. Failure to pay attention will cause misunderstanding.
Official explanation: Apply a method of an object to replace the current object with another object.
The difference between apply and call is the second parameter. apply is an array or arguments object. And call is any type separated by commas.

The most confusing part about the apply and call methods is also the characteristics of apply and call. But it's best not to abuse it.
Can change the object of the calling function. As in the following example, the this keyword is used in the function. At this time, this represents the first parameter of the apply and call functions.






2. About closures
prototype.js in Class.create,bind The closure feature of JavaScript is used in etc. But overall prototype.js doesn't use the powerful closure feature much. You can refer to my translated article to learn about closures.
3. Two methods that disgust me

(1)
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
I hate writing javascript in the style of other languages. Using this method to construct a custom class does not feel very convenient. Reducing the number of lines of code will only make it difficult to understand and define an additional initialize method.
Actually, this is a bit far-fetched, but modifying the prototype object of Object is a bit too much.
(2) Object.prototype.extend
First of all, the name of extend will cause ambiguity to people who are familiar with Java. Modifying the prototype of Object is unreasonable. I don’t know what the author thought about it. Trouble starts when you for in loop objects. Someone may ask you what you are doing for in. I used both DWR and prototype.js in a project. The JavaScript objects returned by dwr all have an extra exetend attribute, which requires special processing. I have compared the implementation of inheritance in dojo and prototype.js before, and now I understand the truth. For a language like JavaScript that does not have static type checking and has loose syntax, if you choose a certain JS library, you must also adapt to the author's style of writing JavaScript. The author of prototype.js is very good at using extend. If we don't think it is just a property copy function, it is good to read more about the code of prototype.js.
4. About function binding

The class library provides two methods: Function.prototype.bind and Function.prototype.bindAsEventListener. First we conceptually explain one of these two methods.
Any function can call these two methods; the parameters are JavaScript objects or element objects on the web page; the return type is a function object.
Originally, I am a function, and the return function is still a function. What is the difference between these two functions? Looking at the implementation code, the key is still the code of the applycall function. In fact, this is just a conversion of the object called by the method.



Test


This is an example from https://compdoc2cn.dev.java.net/. Personally, it doesn’t make sense. Makes me a little disgusted with bind, bindAsEventListener. (Javascript is like this, everyone knows the syntax, but the code written is really different) Look at the following code:




Test



As can be seen from the above code, bind/bindAsEventListener just wraps the apply/call method and changes the calling object of the method. For example, you can convert the obj.getName method into any object call, and let the method be triggered by the form element. (The only difference between bind and bindAsEventListener is the parameters of the return function)
These two methods can also be used to reuse methods between objects to achieve a concept similar to inherited methods. Looking at the following code, it is actually quite boring.






I have never read the extension project code of prototype.js, and I don’t know the best practices of bind.., let’s dig together Bar. But you must not understand bind/bindAsEventListener from the meaning of binding, which may make you more confused. Understand the essence from apply/call. Apply a method of an object to replace the current object with another object.

5. About event registration
<script></script><script> <BR> function Obj(){ <BR> this.value="对象!"; <BR> } <BR> var value="global 变量"; <BR> function Fun1(){ <BR> alert(this.value); <BR> } <BR> window.Fun1(); <BR> Fun1.apply(window); <BR> Fun1.apply($('myText')); <BR> Fun1.apply(new Obj()); <BR></script> <script></script><script> <BR> var CheckboxWatcher = Class.create(); <BR> CheckboxWatcher.prototype = { <BR> initialize: function(chkBox, message) { <BR> this.chkBox = $(chkBox); <BR> this.message = message; <BR> this.chkBox.onclick = this.showMessage.bindAsEventListener(this); <BR> }, <BR> showMessage: function(evt) { <BR> alert(this.message + ' (' + evt.type + ')'); <BR> } <BR> }; <BR>new CheckboxWatcher('myChk','message!!!!'); <BR>//$('myChk').onclick=function(){}; <BR></script> Test <script></script><script> <BR>function Class(){ <BR> this.name="class"; <BR>} <BR>Class.prototype.getName=function(){ <BR> alert(this.name); <BR>} <BR>var obj=new Class(); <BR>//$('myChk').onclick=obj.getName; <BR>$('myChk').onclick=obj.getName.bind(obj); <BR>//$('myChk').onclick=obj.getName.bind($('myChk')); <BR></script> <script></script><script> <BR>function Class1(name){ <BR> this.name=name; <BR>} <BR>Class1.prototype.getName=function(){ <BR> alert(this.name); <BR>} <BR>function Class2(name){ <BR> this.name=name; <BR>  this.getName=Class1.prototype.getName.bind(this); <BR>} <BR>var obj1=new Class2("yql"); <BR>obj1.getName(); <BR>var obj2=new Object(); <BR>obj2.name="zkj"; <BR>obj2.fun=Class1.prototype.getName.bind(obj2); <BR>obj2.fun(); <BR></script>Execute the above code and you will understand the Event. The difference between observe and bind/bindAsEventListener: <script></script> (1) Obviously Event.observe has limitations and can only handle simple functions, and there cannot be things like this in the function. <script> <BR>Event.observe(myChk, 'click', showMessage, false); <BR>//$('myChk').onclick=showMessage; <BR>//$('myChk').onclick=showMessage.bind(); <BR>$('myChk').onclick=showMessage.bind($('myChk')); <BR>function showMessage() { <BR> alert(this.value); <BR>} <BR></script> (2) AddEventListener/attachEvent is used internally in Event.observe. Multiple functions can be added to a trigger event (window.onload). bind is overridden.

6. 이벤트 모니터링 모범 사례
분명히 Prototype.js에서 제공하는 이벤트 등록 방법은 그다지 완전하지 않습니다. 그렇다면 도장의 시간 등록(중국어 버전)을 살펴보세요. 저처럼 도장에 대해 관망하는 태도를 갖고 있는 사람이 많을 것 같습니다.
클로저에 대한 이전 소개를 읽으셨다면 다음 코드를 보셨을 것입니다.
다음 코드를 보기 전에 웹페이지의 모든 요소에 대해 브라우저가 객체를 생성한다는 점을 강조하고 싶습니다(참조). (제 생각에는) 이러한 개체와 여러분이 만든 JavaScript 개체의 차이점은 이벤트 리스너가 있고 마우스 및 키보드 이벤트에 응답한다는 것입니다. 다음 코드를 사용하면 이벤트 청취 코드를 자바스크립트 코드로 쉽게 변환할 수 있습니다.

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 메소드 본문.
}
DhtmlObject.prototype.doMouseOver = function(event, element){
... // doMouseOver 메서드 본문.
}
DhtmlObject.prototype.doMouseOut = function(event, element){
... // doMouseOut 메서드 본문.
}

갖고 싶습니다. time 위의 아이디어를 사용하여 웹 페이지에서 플로팅 박스를 드래그하는 코드를 구현합니다(사실 이미 많이 있습니다). 계속하려면...

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template