JS Learning note 04-es6 function (arrow function with this), class

Source: Internet
Author: User
Tags es6 class

Arrow functions

Making short single-line functions easier to write and read
A normal function can be a function declaration or function expression, but an arrow function is always an expression
Normal function (converts the name to uppercase)

const upperNames = [‘Fish‘, ‘RedHands‘, ‘Sugarbeans‘].map(function(name) {   return name.toUpperCase();});

convert function to arrow function, function body has only one expression , shorthand body syntax
1) Delete the keyword function
2) Remove the parentheses
3) Remove the left and right curly braces
4) Delete the keyword return
5) Remove the semicolon
6) Add an arrow (= =) between the argument list and the function body

const upperNames = [‘Fish‘, ‘RedHands‘, ‘Sugarbeans‘].map( name => name.toUpperCase() );

Multiple lines of code are required within the body of the arrow function, general body Syntax
1) It puts the function body inside the curly braces
2) Return content is also required.

The arrow functions are stored in the variable

multiple or 0 parameters you need to put the parameter list in ()
Sometimes ' _ ' denotes a parameter, but does not use it

const greet = name=>`Hello ${name}`;greet("fish");const students = (name,age) =>`Hello My name is ${name}, I‘m ${age}`;students("fish",19);const firstDemo = _=>`Hello world!`;  //参数为"_"
This in the arrow function

Inside the arrow function, the value of this is the same as the value of this outside the function

function IceCream() {  this.scoops = 0;}IceCream.prototype.addScoop = function() {  const cone = this; // 设置 `this` 给 `cone`变量 ,如果使用箭头函数就不需要  setTimeout(function() {    cone.scoops++; // 引用`cone`变量    console.log(‘scoop added!‘);  }, 500);};const dessert = new IceCream();dessert.addScoop(); //500毫秒之后,dessert.scoops = 1

The above closure code with the arrow function can not need the variable cone

function IceCream() {  this.scoops = 0;}// 为 IceCream 添加 addScoop 方法IceCream.prototype.addScoop = function() {  setTimeout(()  => {   this.scoops++; //直接使用函数外的对象    console.log(‘scoop added!‘);  }, 500);};
function parameter Default value
function getName(name){    name = (typeof name !== ‘undefined‘) ? name : ‘fish‘;     return name;}function getName(name = "fish") {    // 添加等号 ( = ) 以及默认值    return name;}
Default and deconstructed arrays
// = []  防止调用无参函数报错 Cannot read property ‘Symbol(Symbol.iterator)‘ of undefined function createGrid([width = 5, height = 5] = []) {  //=[], createGrid()可以直接使用  return `Generating a grid of ${width} by ${height}`;}
Default and Deconstruction objects

function can make an object a default parameter and use an object to deconstruct
Because the array is location-based, an advantage of the object's default value is to skip the parameter for processing, as opposed to the array default
Arrays are location-based and need to pass in undefined to skip parameters

//={} 同数组一样function createSundae({scoops = 1, toppings = [‘Hot Fudge‘]} = {}) {  const scoopText = scoops === 1 ? ‘scoop‘ : ‘scoops‘;  return `Your sundae has ${scoops} ${scoopText} with ${toppings.join(‘ and ‘)} toppings.`;}
ES6 Class Creation Classes

ES5 Constructor creates "class"

function Plane(numEngines) {  //Plane 函数是一个构造函数  this.numEngines = numEngines;  this.enginesActive = false;}// 由所有实例 "继承" 的方法Plane.prototype.startEngines = function () {  console.log(‘starting engines...‘);  this.enginesActive = true;};const richardsPlane = new Plane(1); //使用new创建新的 Plane 对象richardsPlane.startEngines();const jamesPlane = new Plane(4);jamesPlane.startEngines();

Code after the new class syntax is written

class Plane { //  constructor(numEngines) {    this.numEngines = numEngines;    this.enginesActive = false;  }startEngines() {    console.log(‘starting engines…‘);    this.enginesActive = true;  }}typeof Plane; // function        新语法定义的类也只是一种函数
static method Statics

Static methods are not inherited by instances, but are called directly through the class.
Three call methods, which are not related to the instance
1) The parent class calls directly
2) The subclass inherits the parent class and then calls
3) Subclasses are called through Super objects

class Foo {  static classMethod() {    return ‘hello‘;  }}Foo.classMethod();  //hello 父类直接调用class Bar extends Foo {}Bar.classMethod();  //hello 子类继承父类调用class Cla extends Foo {    return super.classMethod(); //hello super调用}
Super and extends

Subclass inherits the parent class using the keyword extends
In the construction method, super is used as a function, if the constructor of the subclass has this and super,super must be placed in front of this. In the method of a subclass, super is used as an object, calling the method of the parent class

  class Tree {///ES6 Create class, subclass constructor (size = ' ten ', leaves = {spring: ' Green ', Summer: ' Green ', Fall: ' Orang    E ', winter:null}) {this.size = size;    This.leaves = leaves;  This.leafcolor = null;    }changeseason (season) {this.leafcolor = This.leaves[season];    if (season = = = ' Spring ') {this.size + = 1;    }}}class Maple extends Tree {//inherits the parent class constructor (Syrupqty = $, size, leaves) {super (size, leaves);//Super in construction method  This.syrupqty = Syrupqty; }changeseason (season) {Super.changeseason (season);//Super If in Subclass method (season = = = ' Spring ') {this.syrupqty + = 1    ;  }} Gathersyrup () {this.syrupqty-= 3; }}
function Tree(size, leaves) {  //ES5创建类,子类  this.size = size || 10;  this.leaves = leaves || {spring: ‘green‘, summer: ‘green‘, fall: ‘orange‘, winter: null};  this.leafColor;}Tree.prototype.changeSeason = function(season) {  this.leafColor = this.leaves[season];  if (season === ‘spring‘) {    this.size += 1;  }}function Maple (syrupQty, size, leaves) {  //子类  Tree.call(this, size, leaves);  //使用父类的属性  this.syrupQty = syrupQty || 15;}Maple.prototype = Object.create(Tree.prototype); //函数原型设置为基类原型Maple.prototype.constructor = Maple;//重新建立constructor和构造函数的连接Maple.prototype.changeSeason = function(season) {  Tree.prototype.changeSeason.call(this, season);  //重写父类的方法  if (season === ‘spring‘) {    this.syrupQty += 1;  }}Maple.prototype.gatherSyrup = function() {  this.syrupQty -= 3;}

Tree.call (this, size, leaves);
Maple.prototype = Object.create (Tree.prototype);
Maple.prototype.constructor = Maple;

JS Learning note 04-es6 function (arrow function with this), class

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.