ES6下的Function.bind方法
在JavaScript的使用中,this的指向问题始终是一个难点。不同的调用方式,会使this指向不同的对象。而使用call,apply,bind等方式,可改变this的指向,完成一些令人惊叹的黑魔法
最近了解了一下Function对象下的bind方法,同时对JavaScript对象下this指向,call,apply等方法有了更深刻的了解
function.apply(thisArg,[argsArray])
thisArg: function函数运行时的this值
argsArray: 一个数组或者类数组对象,其中的数组元素将作为单独的参数传给function函数
returns: 调用this值和和参数产生的结果
下面讲述一些apply的简单使用
- 用apply 将数组push 进另一个数组
1 |
var elements = [1,2,3] |
- 找出数组中最大/最小的数
1 |
var nums = [1,2,3,4,5] |
function.call(thisArg,arg1,args2,args3)
thisArg: function函数运行时的this值
arg1, arg2, …: 指定的参数列表。
returns: 调用this值和和参数产生的结果
function.call
与 function.apply
的本质其实是一样的。只有一个区别,就是 call()
方法接受的是一个参数列表,而 apply()
方法接受的是一个包含多个参数的数组
function.bind(thisArg,arg1,arg2,…)
thisArg: function函数运行时指向的this值
arg1,arg2,…: 当目标函数被调用时,预先添加到绑定函数的参数列表中的参数。
returns: 返回一个原函数的拷贝,并拥有指定的this值和初始参数。
- 创建绑定函数
bind()
的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为bind()
的参数写在this
后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。
1 |
this.x = 9; |
bind函数的初步实现
bind的实质,其实为call的语法糖。我们只需返回一个利用Function.call改变this指向的函数即可
1 |
Function.prototype.bindDemo = function(obj,args){ |
将bind函数绑定在原型链上
上面的函数已经可以解决一些实际问题,但依旧存在一些问题。当thisArg为原型链上的对象时,bind对象需要能调用原型上的方法。
1 |
Function.prototype.bindDemo = function(obj,args){ |
最新文章
- [SQL] SQL SERVER基础语法
- iOS 如何使用自定义字体
- Android:简单实现ViewPager+TabHost+TabWidget实现导航栏导航和滑动切换
- aix 文件大小相关查询
- Linux 常用命令使用方法大搜刮(转)
- 对ExtJS4应用 性能优化的几点建议
- ORA-12516: TNS: 监听程序找不到符合协议堆栈要求的可用处理程”的异常
- HtmlCleaner CleanerProperties 参数配置(转自macken博客,链接:http://macken.iteye.com/blog/1579809)
- display:flex css
- 新概念英语(1-37)Making a bookcase
- CS通用项目系统搭建——三层架构第二天 (补一篇完整的SqlHelper)
- python---redis实现自定义session
- vue中使用vw适配移动端
- Python自动化开发 - 函数式编程
- VS2015+OpenGL4.0开发编译时弹出错误:glaux.lib(tk.obj) : error LNK2019: 无法解析的外部符号 _sscanf,该符号在函数 _GetRegistrySysColors@8 中被引用
- iptables与SELinux
- C#指南,重温基础,展望远方!(8)C#数组
- Spring定时器Quartz的使用
- Python学习---重点模块之logging
- visual studio 2017无建模项目?
热门文章
- 后端Springboot前端VUE实现Excel导入功能
- Django知识点集合
- 17.3.10--C语言运行的步骤
- Python7DAY-基础语法.md
- git 推送到github最常用命令
- c#学习笔记04——ADO.NET
- 爬虫加入数据post请求
- 二、Shell脚本高级编程实战第二部
- 吴裕雄--天生自然python TensorFlow图片数据处理:No module named 'tensorflow.examples.tutorials'解决办法
- 吴裕雄--天生自然 PYTHON3开发学习:集合