浅谈JS中几种轻松处理'this'指向方式


Posted in Javascript onSeptember 16, 2019

我喜欢在JS中更改函数执行上下文的指向,也称为 this 指向。

例如,咱们可以在类数组对象上使用数组方法:

const reduce = Array.prototype.reduce;

function sumArgs() {
 return reduce.call(arguments, (sum, value) => {
  return sum += value;
 });
}

sumArgs(1, 2, 3); // => 6

另一方面,this 很难把握。

咱们经常会发现自己用的 this 指向不正确。下面的教你如何简单地将 this 绑定到所需的值。

在开始之前,我需要一个辅助函数execute(func),它仅执行作为参数提供的函数。

function execute(func) {
 return func();
}

execute(function() { return 10 }); // => 10

现在,继续理解围绕this错误的本质:方法分离。

1.方法分离问题

假设有一个类Person包含字段firstName和lastName。此外,它还有一个方法getFullName(),该方法返回此人的全名。如下所示:

function Person(firstName, lastName) {
 this.firstName = firstName;
 this.lastName = lastName;

 this.getFullName = function() {
  this === agent; // => true
  return `${this.firstName} ${this.lastName}`;
 }
}

const agent = new Person('前端', '小智');
agent.getFullName(); // => '前端 小智'

可以看到Person函数作为构造函数被调用:new Person('前端', '小智')。 函数内部的 this 表示新创建的实例。

getfullname()返回此人的全名:'前端 小智'。正如预期的那样,getFullName()方法内的 this 等于agent。

如果辅助函数执行agent.getFullName方法会发生什么:

execute(agent.getFullName); // => 'undefined undefined'

执行结果不正确:'undefined undefined',这是 this 指向不正确导致的问题。

现在在getFullName() 方法中,this的值是全局对象(浏览器环境中的 window )。 this 等于 window,${window.firstName} ${window.lastName} 执行结果是 'undefined undefined'。

发生这种情况是因为在调用execute(agent.getFullName)时该方法与对象分离。 基本上发生的只是常规函数调用(不是方法调用):

execute(agent.getFullName); // => 'undefined undefined'

// 等价于:

const getFullNameSeparated = agent.getFullName;
execute(getFullNameSeparated); // => 'undefined undefined'

这个就是所谓的方法从它的对象中分离出来,当方法被分离,然后执行时,this 与原始对象没有连接。

为了确保方法内部的this指向正确的对象,必须这样做

  1. 以属性访问器的形式执行方法:agent.getFullName()
  2. 或者静态地将this绑定到包含的对象(使用箭头函数、.bind()方法等)

方法分离问题,以及由此导致this指向不正确,一般会在下面的几种情况中出现:

回调

// `methodHandler()`中的`this`是全局对象
setTimeout(object.handlerMethod, 1000);

在设置事件处理程序时

// React: `methodHandler()`中的`this`是全局对象
<button onClick={object.handlerMethod}>
 Click me
</button>

接着介绍一些有用的方法,即如果方法与对象分离,如何使this指向所需的对象。

2. 关闭上下文

保持this指向类实例的最简单方法是使用一个额外的变量self:

function Person(firstName, lastName) {
 this.firstName = firstName;
 this.lastName = lastName;

 const self = this;

 this.getFullName = function() {
  self === agent; // => true
  return `${self.firstName} ${self.lastName}`;
 }
}

const agent = new Person('前端', '小智');

agent.getFullName();    // => '前端 小智'
execute(agent.getFullName); // => '前端 小智'

getFullName()静态地关闭self变量,有效地对this进行手动绑定。

现在,当调用execute(agent.getFullName)时,一切工作正常,因为getFullName()方法内 this 总是指向正确的值。

3.使用箭头函数

有没有办法在没有附加变量的情况下静态绑定this? 是的,这正是箭头函数的作用。

使用箭头函数重构Person:

function Person(firstName, lastName) {
 this.firstName = firstName;
 this.lastName = lastName;

 this.getFullName = () => `${this.firstName} ${this.lastName}`;
}

const agent = new Person('前端', '小智');

agent.getFullName();    // => '前端 小智'
execute(agent.getFullName); // => '前端 小智'

箭头函数以词法方式绑定this。 简单来说,它使用来自其定义的外部函数this的值。

建议在需要使用外部函数上下文的所有情况下都使用箭头函数。

4. 绑定上下文

现在让咱们更进一步,使用ES6中的类重构Person。

class Person {
 constructor(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
 }

 getFullName() {
  return `${this.firstName} ${this.lastName}`;
 }
}

const agent = new Person('前端', '小智');

agent.getFullName();    // => '前端 小智'
execute(agent.getFullName); // => 'undefined undefined'

不幸的是,即使使用新的类语法,execute(agent.getFullName)仍然返回“undefined undefined”。

在类的情况下,使用附加的变量self或箭头函数来修复this的指向是行不通的。

但是有一个涉及bind()方法的技巧,它将方法的上下文绑定到构造函数中:

class Person {
 constructor(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = this.getFullName.bind(this);
 }

 getFullName() {
  return `${this.firstName} ${this.lastName}`;
 }
}

const agent = new Person('前端', '小智');

agent.getFullName();    // => '前端 小智'
execute(agent.getFullName); // => '前端 小智'

构造函数中的this.getFullName = this.getFullName.bind(this)将方法getFullName()绑定到类实例。

execute(agent.getFullName) 按预期工作,返回'前端 小智'。

5. 胖箭头方法

bind 方式有点太过冗长,咱们可以使用胖箭头的方式:

class Person {
 constructor(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
 }

 getFullName = () => {
  return `${this.firstName} ${this.lastName}`;
 }
}

const agent = new Person('前端', '小智');

agent.getFullName();    // => '前端 小智'
execute(agent.getFullName); // => '前端 小智'

胖箭头方法getFullName =() =>{…}绑定到类实例,即使将方法与其对象分离。

这种方法是在类中绑定this的最有效和最简洁的方法。

6. 总结

与对象分离的方法会产生 this 指向不正确问题。静态地绑定this,可以手动使用一个附加变量self来保存正确的上下文对象。然而,更好的替代方法是使用箭头函数,其本质上是为了在词法上绑定this。

在类中,可以使用bind()方法手动绑定构造函数中的类方法。当然如果你不用使用 bind 这种冗长方式,也可以使用简洁方便的胖箭头表示方法。

原文:https://github.com/valentinogagliardi/Little-JavaScript-Book/blob/v1.0.0/manuscript/chapter5.md

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript 不间断的图片滚动并可点击
Jan 15 Javascript
javascript将url中的参数加密解密代码
Nov 17 Javascript
jQuery中before()方法用法实例
Dec 25 Javascript
Jquery实现textarea根据文本内容自适应高度
Apr 03 Javascript
浅析js中substring和substr的方法
Nov 09 Javascript
jquery ztree实现树的搜索功能
Feb 25 Javascript
分享JS数组求和与求最大值的方法
Aug 11 Javascript
深入理解Javascript中的作用域链和闭包
Apr 25 Javascript
微信小程序-form表单提交代码实例
Apr 29 Javascript
详解vue中使用protobuf踩坑记
May 07 Javascript
Vue仿微信app页面跳转动画效果
Aug 21 Javascript
微信小程序本地存储实现每日签到、连续签到功能
Oct 09 Javascript
使用xampp将angular项目运行在web服务器的教程
Sep 16 #Javascript
在layui.use 中自定义 function 的正确方法
Sep 16 #Javascript
使用VUE实现在table中文字信息超过5个隐藏鼠标移到时弹窗显示全部
Sep 16 #Javascript
js实现无限瀑布流实例方法
Sep 16 #Javascript
策略模式实现 Vue 动态表单验证的方法
Sep 16 #Javascript
jQuery设置下拉框显示与隐藏效果的方法分析
Sep 15 #jQuery
Vue实现滑动拼图验证码功能
Sep 15 #Javascript
You might like
php 使用array函数实现分页
2015/02/13 PHP
微信红包随机生成算法php版
2016/07/21 PHP
如何利用预加载优化Laravel Model查询详解
2017/08/11 PHP
PHP回调函数概念与用法实例分析
2017/11/03 PHP
基于jQuery选择器的整理集合
2013/04/26 Javascript
jquery手风琴特效插件
2015/02/04 Javascript
jQuery Ajax使用实例
2015/04/16 Javascript
JavaScript简单修改窗口大小的方法
2015/08/03 Javascript
常用的Javascript数据验证插件
2015/08/04 Javascript
javascript实现拖放效果
2015/12/16 Javascript
初步使用bootstrap快速创建页面
2016/03/03 Javascript
JQuery fileupload插件实现文件上传功能
2016/03/18 Javascript
node.js中 stream使用教程
2016/08/28 Javascript
javascript ASCII和Hex互转的实现方法
2016/12/27 Javascript
Vue.js基础学习之class与样式绑定
2017/03/20 Javascript
Vue.js使用$.ajax和vue-resource实现OAuth的注册、登录、注销和API调用
2017/05/10 Javascript
EasyUI在Panel上动态添加LinkButton按钮
2017/08/11 Javascript
深入理解Vue2.x的虚拟DOM diff原理
2017/09/27 Javascript
VueJs监听window.resize方法示例
2018/01/17 Javascript
解决antd日期选择组件,添加value就无法点击下一年和下一月问题
2020/10/29 Javascript
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
2017/09/08 Python
Python Django框架实现应用添加logging日志操作示例
2019/05/17 Python
在python Numpy中求向量和矩阵的范数实例
2019/08/26 Python
解决jupyter notebook显示不全出现框框或者乱码问题
2020/04/09 Python
在python中使用nohup命令说明
2020/04/16 Python
python爬取抖音视频的实例分析
2021/01/19 Python
CSS3实现菜单悬停效果
2020/11/17 HTML / CSS
Timberland美国官网:全球领先的户外品牌
2016/08/15 全球购物
购买中国最好的电子产品:Geekbuying
2018/03/13 全球购物
伦敦高达60%折扣的钻石珠宝商:Purely Diamonds
2018/06/24 全球购物
外企测试工程师面试题
2015/02/01 面试题
党员年终民主评议的自我评价
2013/11/05 职场文书
优秀教师先进事迹材料
2014/12/15 职场文书
法定授权委托证明书
2015/06/18 职场文书
2019消防宣传标语!
2019/07/10 职场文书
聊聊CSS粘性定位sticky案例解析
2022/06/01 HTML / CSS