2、Es常用语法 箭头函数、类

1、箭头函数

什么是箭头函数

箭头函数的语法非常简单,看一下最简单的箭头函数表示法
() => console.log(‘Hello‘)
() => {console.log(‘Hello‘)}

等同于

function(){
console.log(‘hello‘)
}

箭头函数里的this:

  箭头函数里的this指向定义时的作用域

  普通函数里的this指向调用者的作用域

箭头函数不绑定arguments

let arrowfunc = () => console.log(arguments.length)
arrowfunc()
//output
arguments is not defined

如果此时我们想要获得函数的参数可以借助扩展运算符“...”

let arrowfunc = (...theArgs) => console.log(theArgs.length)
arrowfunc(1,2)
//output
2

2、类

js生成实例对象的传统方式是通过构造函数:

function Point (x, y){
       this.x = x;
       this.y = y;
}

Point.prototype.toString = function(){
        return `( ${this.x} , ${this.y} )`
}
var p = new Point(1,2);
p.toString();
//"(1,2)"

Es6通过class关键字定义类

前面不需要加function这个关键字,直接将函数定义放进去就行了 ,另外,方法之间不需要逗号分隔;

//定义类

class Point {
    constructor (x, y) {
        this.x =x;
        this.y =y;
      }

        toString () {
        return `( ${this.x}, ${this.y} )`;
       }
       toValue () {
        return this.x+this.y;
       }
}
var p = new Point(1,2);
p.toString();
//"(1,2)"
p.toValue();
//3

constructor方法

constructor方法是是类的默认方法,通过new命令生成对象实例时,自动调用该方法,一个类必须有constructor方法,如果没有显示定义,一个空的constructor方法会被默认添加:

1 class Point{
2 }
3
4 //等同于
5 class Point {
6      constructor () { }
7 }
8 //定义了一个空的类Point,JavaScript 引擎会自动为它添加一个空的constructor方法。
constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象;
class Person {
      constructor  () {
            return Object.create(null);
         }
}

new Person() instanceof Person
//false
//实例      instanceof 构造函数  用来判断实例是否是构造函数的实例

构造函数的prototype属性,在ES6的类上继续存在,实际上,类的所有方法都定义在类的prototype属性上面;

//定义类
class Point {
        constructor (x, y) {
           this.x =x;
            this.y =y;
          }
      toString () {
          return `(${this.x},${this.y})`;
       }
}

var point = new Point(1,2);

point.toString();//(1,2)

point.hasOwnProperty("x"); //true
point.hasOwnProperty("y"); //true
point.hasOwnProperty("toString");//fasle
point.__proto__.hasOwnProperty("toString");//true

clss表达式

和函数一样,类也可以使用表达式的形式定义:

const MyClass = class Me{
        getClassName () {
               return Me.name ;
            }
};

let inst  = new MyClass();
inst .getClassName();
//"Me"
Me.name
//ReferenceError :Me is not defined

Me只有在Class内部有定义;
如果类的内部没有用到的话,可以省略Me,可以改写成:

const MyClass = class {
    getClassName () {
               return  ;
            }
}
采用Class表达式,可以写出立即执行Class
let person = new class {
      constructor (name) {
          this.name = name ;
          }

       sayName() {
                  console.log(this.name);
          }
}("张三");

person.sayName();
//"张三"

class不存在变量提升

new Foo();//ReferenceError
class Foo();

this的指向

类的方法内部如果含有this,他默认指向类的实例,但是,必须非常小心,一旦单独使用该方法,可能会报错;

class Logger {
  printName(name = ‘there‘) {
    this.print(`Hello ${name}`);
  }

  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property ‘print‘ of undefined

Class 的取值函数(getter)和存值函数(setter)

与 ES5 一样,在“类”的内部可以使用get和set关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为

class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return ‘getter‘;
  }
  set prop(value) {
    console.log(‘setter: ‘+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// ‘getter‘

prop属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。

Class 的静态方法

类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”

class Foo {
  static classMethod() {
    return ‘hello‘;
  }
}

Foo.classMethod() // ‘hello‘

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

Foo类的classMethod方法前有static关键字,表明该方法是一个静态方法,可以直接在Foo类上调用(Foo.classMethod()),而不是在Foo类的实例上调用。如果在实例上调用静态方法,会抛出一个错误,表示不存在该方法。
注意,如果静态方法包含this关键字,这个this指的是类,而不是实例。

class Foo {
  static bar () {
    this.baz();
  }
  static baz () {
    console.log(‘hello‘);
  }
  baz () {
    console.log(‘world‘);
  }
}

Foo.bar() // hello

静态方法bar调用了this.baz,这里的this指的是Foo类,而不是Foo的实例,等同于调用Foo.baz。另外,从这个例子还可以看出,静态方法可以与非静态方法重名。
父类的静态方法,可以被子类继承。

class Foo {
  static classMethod() {
    return ‘hello‘;
  }
}

class Bar extends Foo {
}

Bar.classMethod() // ‘hello

静态方法也是可以从super对象上调用的。

Class 的静态属性和实例属性

静态属性指的是 Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。

class Foo {
}

Foo.prop = 1;
Foo.prop // 1
//Foo类定义了一个静态属性prop,只有这种写法可行,因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性。

(1)类的实例属性
类的实例属性可以用等式,写入类的定义之中

class MyClass {
  myProp = 42;

  constructor() {
    console.log(this.myProp); // 42
  }
}
//myProp就是MyClass的实例属性。在MyClass的实例上,可以读取这个属性。

原文地址:https://www.cnblogs.com/pengsq/p/10153099.html

时间: 2024-08-28 16:51:15

2、Es常用语法 箭头函数、类的相关文章

006 python语法_002 函数/类/模块

''' 时间:2018/10/11 目录: 一: 函数 1 定义函数 2 空函数 3 参数 - 检查 4 参数 - 返回多个值 5 参数 - 默认参数 二: 类 1 语法1 2 语法2 三: 模块 1 ''' 一: 函数 1 定义函数 #coding:utf-8 def myAbs(nNum): if nNum >= 0: return nNum else: return -nNum nNum = myAbs(33) print(nNum) nNum = myAbs(-33) print(nNu

JavaScript 箭头函数:适用与不适用场景

JavaScript 箭头函数:适用与不适用场景现代 JavaScript 中最引人注目的功能之一是引入了箭头函数,用 => 来标识. 这种函数有两大优点 – 非常简洁的语法,和更直观的作用域和 this的绑定. 这些优点有时导致箭头函数比其他形式的函数声明更受欢迎. 例如,受欢迎的 airbnb eslint 配置 会在您创建匿名函数时强制使用JavaScript箭头函数. 然而,就像工程中的任何东西一样,箭头函数优点很明显,同时也带来了一些负面的东西. 使用他们的时候需要权衡一下. 学习如何

ES6——箭头函数与普通函数的区别

ES6标准新增了一种新的函数:Arrow Function(箭头函数). 为什么叫Arrow Function?因为它的定义用的就是一个箭头: 语法: //1.没有形参的时候 let fun = () => console.log('我是箭头函数'); fun(); //2.只有一个形参的时候()可以省略 let fun2 = a => console.log(a); fun2('aaa'); //3.俩个及俩个以上的形参的时候 let fun3 = (x,y) =>console.lo

PHP 7.4 新语法:箭头函数

短闭包,也叫做箭头函数,是一种用 php 编写的短函数.当向函数中传递闭包时,这个功能是非常有用的,比如使用 array_map 或是 array_filter 函数时. 译者注:PHP7.4 计划于今年底发布,请见 Wiki:PHP 基础信息:发行计划 这就是它们看起来的样子: 1 // Post 对象的集合 2 $posts = [/* … */]; 3 4 $ids = array_map(fn($post) => $post->id, $posts); 5 而以前,你必须这样写: 6

数据库基础知识整理,常用函数及常用语法

1常用数据库聚合函数max()min()sum()avg()count() 2字符串处理函数len() 与 datalength()  区别:len是返回字符长度  datalength是返回字节长度LTrim()  RTrim() Trim ()isnull(@FilterStr,N'')如果时空将其替换 charindex(N';', @TmpList)返回字符串中表达式的起始位置而不是indexpaitndex('%ssd%',@temp) 与charindex作用基本类似 substri

ES6语法~解构赋值、箭头函数

2015年6月17日 ECMAScript 6发布正式版本 打开VSCode终端powershell:ctrl+` 1.         定义变量:let 使用var 定义的变量没有{ }限制,在条件中定义的i,全局中都可以使用,造成变量污染,有变量提升预解析作用,只提升变量名,不提升值!降低js代码的可阅读性 相同作用域内,let不允许重复声明变量!!否则报错!!但可以更改变量值 使用let定义的变量:不会有变量提升,必须先定义后使用,否则先使用会报错: ReferenceError 在for

ES6常用语法

ECMAScript 6(以下简称ES6)是JavaScript语言的下一代标准.因为当前版本的ES6是在2015年发布的,所以又称ECMAScript 2015. 也就是说,ES6就是ES2015. 虽然目前并不是所有浏览器都能兼容ES6全部特性,但越来越多的程序员在实际项目当中已经开始使用ES6了.所以就算你现在不打算使用ES6,但为了看懂别人的你也该懂点ES6的语法了... 在我们正式讲解ES6语法之前,我们得先了解下Babel. Babel Babel是一个广泛使用的ES6转码器,可以将

第79篇 Vue第一篇 ES6的常用语法

01-变量的定义 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> // var somedody; // console.log(somebody); // var somebody = &qu

MySQL 储存过程-原理、语法、函数详细说明

Mysql储存过程是一组为了完成特定功能的SQL语句集,经过编译之后存储在数据库中,当需要使用该组SQL语句时用户只需要通过指定储存过程的名字并给定参数就可以调用执行它了,简而言之就是一组已经写好的命令,需要使用的时候拿出来用就可以了.想要快速的了解Mysql储存过程吗,就一同看一下下文的"Mysql储存过程-原理.语法.函数详细说明"吧! 一.Mysql储存过程简介:储存过程是一个可编程的函数,它在数据库中创建并保存.它可以有SQL语句和一些特殊的控制结构组成.当希望在不同的应用程序