Inheritance of objects in javascript [repost]_javascript skills
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 위의 아이디어를 사용하여 웹 페이지에서 플로팅 박스를 드래그하는 코드를 구현합니다(사실 이미 많이 있습니다). 계속하려면...

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
