谈谈ES6 class中箭头函数定义的方法

  ES6 的class,emmm~javascript

  看软大大的书知道类的内部全部定义的方法,都是不可枚举的(non-enumerable)html

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }
}
const point = new Point()
Object.keys(point) 

// []

  这是在chrome控制台执行的代码,能够看到point实例上并无可枚举的属性及方法。这一方面是由于类的方法都定义在prototype对象上面,另外一方面是不可枚举的哈哈哈哈哈java

   好吧,并无证实是不可枚举的  chrome

 

  再写段代码看看数组

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }
}

Object.keys(Point.prototype)
// []
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

  

  ok,下面来讲正事  函数

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }

  say = () =>{
    // ...
  }
}
const point = new Point()
Object.keys(point)

// ["say"]

  woc,怎么回事??不是说类的方法都定义在prototype对象上面吗?嘤嘤嘤,太难了吧。this

  虽然很难,可是我想试着分析一下。prototype

  Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组code

  首先从自身开始分析(站在实例的角度上),孔子告诉咱们出了事先从自身找问题。定义在类内部的方法怎么会跑到我这个实例身上呢(cao)?好难,仍是先看看箭头函数吧。htm

  ok,先来看看箭头函数。

  箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象

  this指向的固定化,并非由于箭头函数内部有绑定this的机制,实际缘由是箭头函数根本没有本身的this,致使内部的this就是外层代码块的this

  。。。。

  看看箭头函数转成 ES5 的代码

  

// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

// ES5
function foo() {
  var _this = this;

  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}

  ok,箭头函数的this其实就是包裹它的第一个非箭头函数的函数的this值。

 

  再回头看看上面举的例子

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }

  say = () =>{
    // ...
  }
}

//其实就等同于下面这种写法
class Point {
  constructor(x, y) {
    // ...
    this.say = () => {
      // ...
    }
  }

  toString() {
    // ...
  }
}

  

  最终版

class Point {
  constructor(x, y) {
    // ...
    this.say = () => {
      // ...
    }
  }

  toString() {
    // ...
  }
}

//等同于
class Point {
  constructor(x, y) {
    // ...
    this.say = function() {
      const _this = this
      return function() {}.bind(_this)
    }
  }

  toString() {
    // ...
  }
}

  逻辑不清写得乱七八糟,哭了   (ಥ_ʖಥ)

  

原文出处:https://www.cnblogs.com/tengyijun/p/12105963.html

相关文章
相关标签/搜索