栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

ES6类中的ES6函数,箭头函数和“ this”

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ES6类中的ES6函数,箭头函数和“ this”

重要的是要知道以下语法:

class A {  method = () => {}}

只是在类构造函数中创建实例方法的语法糖:

class A {  constructor() {    this.method = () => {}  }}

注意:该语法尚未成为Javascript语言的正式组成部分(当前处于第3阶段),因此您必须使用Babel这样的编译器来处理它。

this
method
是一流的
A
,因为这是
this
在构造函数中指向(因为箭头的功能继承了它们在规定的范围内的情况下):

class A {  constructor() {    this.method = () => this;  }}const instance = new A();console.log(instance.method() === instance); // true

在类上定义常规(非箭头函数)方法会在类原型(而不是实例)上创建方法,但不会设置任何规则

this
(因为
this
在JS中是动态的,并且取决于函数的调用方式,而不是函数的调用方式)定义)。

class A {  method() {}}console.log(new A().method === A.prototype.method); // true

如果按照上述两种方法之一定义的方法(通过

.
)在类实例上被调用,则按照将
this
函数作为对象的方法调用时绑定方式的规则,
this
在两种情况下都将指向类实例:

class A {  constructor() {    this.methodonInstance = () => this;  }  methodonPrototype() { return this; }}const instance = new A();console.log(  instance.methodonInstance() === instance.methodonPrototype(), // true  instance.methodonPrototype() === instance // true);

上面两个方法声明之间的主要区别在于,实例方法

this
始终
固定在类实例上,而类(原型)方法没有固定(我们可以使用Function.prototype.apply或Function.prototype.call对其进行更改)

class A {  constructor() {    this.methodonInstance = () => this;  }  methodonPrototype() { return this; }}const instance = new A();console.log(  instance.methodonInstance() === instance.methodonPrototype(), // true  instance.methodOnPrototype.call('new this') === 'new this' // true);

this
更改发生在事件处理程序中的常见情况,其中事件处理程序调用传递给它的函数,并将上下文绑定到发生事件的元素(因此,将的值覆盖为
this
被单击的元素或活动原为

对于所有(合成)DOM事件处理程序,这也会在React中发生。

因此,如果我们希望方法的上下文始终指向React组件的实例,则可以使用instance方法。

限制上下文但不使用需要Babel的特殊实例方法语法的另一种方法是,通过在具有绑定上下文的类(原型)方法中创建一个新函数(使用Function.prototype.bind)来直接直接创建实例方法:

class A {  constructor() {    this.methodonInstance = this.methodOnPrototype.bind(this);  }  methodonPrototype() { return this; }}const instance = new A();console.log(  instance.methodonInstance() === instance.methodonPrototype(), // true  instance.methodonPrototype() === instance // true);

这使我们可以获得与使用特殊实例方法语法相同的结果,但使用当前可用的工具(ES2017及以下)。

如果由于某种原因我们想要一个始终绑定到不是该类实例的东西的方法,我们也可以这样做:

class A {  constructor() {    this.method = this.method.bind(console);  }  method() { return this; }}const instance = new A();console.log(  instance.method() === console // true);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616456.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号