In ES6, the function binding and event binding functions of javascript are described in detail. es6javascript

Source: Internet
Author: User
Tags javascript array hasownproperty

In ES6, the function binding and event binding functions of javascript are described in detail. es6javascript

This article describes how javascript in ES6 binds functions to functions and events of classes. We will share this with you for your reference. The details are as follows:

Function binding

The arrow function can bind this object, greatly reducing the call, apply, and bind statements for explicitly binding this object ). However, arrow functions are not applicable to all scenarios. Therefore, ES7 proposes the function bind operator to replace call, apply, and bind calls. Although this syntax is still a proposal of ES7, the Babel Transcoder has supported it.

The function binding operator is a side-by-side double colon (:). The left side of the double colon is an object, and the right side is a function. This operator automatically binds the object on the left as the context (this object) to the function on the right.

Foo: bar; // equivalent to bar. bind (foo); foo: bar (... arguments); // equivalent to bar. apply (foo, arguments); const hasOwnProperty = Object. prototype. hasOwnProperty; function hasOwn (obj, key) {return obj: hasOwnProperty (key );}

If the left side of the double colon is blank and the right side is an object method, it is equivalent to binding the method to the object.

Var method = obj: obj. foo; // equivalent to var method =: obj. foo; let log =: console. log; // equivalent to var log = console. log. bind (console );

Because the double colon operator returns the original object, you can use the chained method.

// Example 1 import {map, takeWhile, forEach} from "iterlib"; getPlayers (): map (x => x. character (): takeWhile (x => x. strength> 100): forEach (x => console. log (x); // Example 2 let {find, html} = jake; document. querySelectorAll ("div. myClass "): find (" p "): html (" hahaha ");

Event binding in class

Overview

ES6 provides classes and provides great help for modularity. Bind events in the class to make the code structure clear, and to use class variables and methods. However, because the Event Callback Function is not triggered by the Instance Object of the class, the Event Callback Function cannot contain the this variable of the callback class. In addition, we do not want the Event Callback Function to be exposed to the outside, so that the caller can call it directly.

Simply put, we hope that:

1. The event callback function must be able to use this variable of the callback class.
2. The event callback function cannot be called directly.

How to compile this class

Solution 1: save this of the class as a local variable

The reference of this is dynamic, but the reference of local variables is clear, and the local variables defined by the function can be used in the entire function. Therefore, we can uselet that = thisSave this variable of the class.

Class A {// bindEvent () {let that = this; this. button1.on ('click', function (e) {this. addClass ('on'); // this indicates the element of the vertex that. doSomething (); // that points to this})} doSomething () {// event processing function} // unbind event unBindEvent () {this. button1.off ();}}

This method is only useful when jquery is used, because the callback function does not need to be provided for the jquery unbinding event, so you can simply turn off. But native js also needs to provide callback functions. Because the same event of the same element can be bound to multiple callback functions, You need to specify which callback function to release.

Solution 2: Use bind () to change the point of this

Class A is available. To add A mousemove event to Class A, write the following code as required:

Class A {// Add event addEvent () {document. addEventListener ('mousemove ', onMouseMove, false);} // Add event removeEvent () {document. removeEventListener ('mousemove ', onMouseMove, false);} // function onMouseMove (event) {console in the event Callback function. log (this); // # document}

However, in this way, the class's this cannot be obtained. This of onMouseMove will point to document. Because the event is added to the document, the document triggers the event and calls onMouseMove for processing. Therefore, this in onMouseMove points to document.

The correct method is:Usebind()The function changes the point of this in onMouseMove, and moves the Event Callback Function outside the class:

Class A {// Add event addEvent () {document. addEventListener ('mousemove ', onMouseMove. bind (this), false);} // Add event removeEvent () {document. removeEventListener ('mousemove ', onMouseMove. bind (this), false) ;}// function onMouseMove (event) {console in the event Callback function. log (this );}

However, there is still a problem, and the event cannot be removed! Becausethis.bind()Each call will return a new function, so:

document.addEventListener( 'mousemove', onMouseMove.bind(this), false );

And

document.removeEventListener( 'mousemove', onMouseMove.bind(this), false );

The second parameter is not the same.

Correct practiceYes: Setbind()Save the result to a variable:

Class A {constructor () {this. _ onMouseMove = onMouseMove. bind (this); // check here} // Add the event addEvent () {document. addEventListener ('mousemove ', this. _ onMouseMove, false);} // Add event removeEvent () {document. removeEventListener ('mousemove ', this. _ onMouseMove, false) ;}// function onMouseMove (event) {console in the event Callback function. log (this );}

How to define Private Event Callback Functions

In Java, methods that do not want to be exposed can be defined as private methods, but ES6 does not provide private methods and can only be simulated in some ways. However, the Event Callback Function is special, because the event is not only defined, but also removed, which brings extra trouble. But there is still a solution:

Use the Symbol variable to define

Const _ onMouseMove = Symbol ("_ onMouseMove"); class A {constructor () {this [_ onMouseMove] = onMouseMove. bind (this);} // Add event addEvent () {document. addEventListener ('mousemove ', this [_ onMouseMove], false);} // Add event removeEvent () {document. removeEventListener ('mousemove ', this [_ onMouseMove], false) ;}// function onMouseMove (event) {console in the event Callback function. log (this );}

Symbol("_onMouseMove")A unique value is generated when the object is created. Therefore, the caller cannot know the value when writing code, you cannot call the method named by this value, so that a private method is defined.

For more information, see this topic: ECMAScript6 (ES6) getting started, JavaScript Array Operation Skills summary, JavaScript character and string operation skills summary, JavaScript data structure and algorithm skills summary, JavaScript errors and debugging skills Summary and javascript object-oriented tutorials

I hope this article will help you with ECMAScript-based programming.

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.