这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
其实所谓 bind 顾名思义就是绑定。bind() 方法会创建一个新函数,当这个新函数被调用时,它的 this 值是传递给 bind() 的第一个参数,它的参数是 bind() 的其他参数和其原本的参数。这么说可能很多人都糊涂了,下面通过这篇文章的示例来给大家详细的介绍下吧。
前言
bind() 接受无数个参数,第一个参数是它生成的新函数的 this 指向,比如我传个 window,不管它在何处调用,这个新函数中的 this 就指向 window,这个新函数的参数就是
的第二个、第三个、第四个.... 第 n 个参数加上它原本的参数。(行吧,我自己都蒙圈了)
- bind()
示例介绍
我们还是看看栗子比较好理解,举个
最基本的使用方法:
- bind()
- this.x = 9;
- var module = {
- x: 81,
- getX: function() {
- return this.x;
- }
- };
- module.getX(); // 返回 81
- var retrieveX = module.getX;
- retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域
- // 创建一个新函数,将"this"绑定到module对象
- // 新手可能会被全局的x变量和module里的属性x所迷惑
- var boundGetX = retrieveX.bind(module);
- boundGetX(); // 返回 81
这里很明显,我们在 window 对象下调用 retrieveX,得到的结果肯定是 window 下的 x,我们把
对象绑定到
- module
的
- retrieveX
上,问题就解决了,不管它在何处调用,
- this
都是指向
- this
对象。
- module
还有
的其他参数,相信第一次接触
- bind()
的朋友看到上面的定义都会蒙圈。
- bind()
还是举个栗子:
- function list() {
- return Array.prototype.slice.call(arguments);
- }
- var list1 = list(1, 2, 3); // [1, 2, 3]
- // 创建一个拥有预设初始参数的函数
- var leadingThirtysevenList = list.bind(undefined, [69, 37], {
- a: 2
- });
- var list2 = leadingThirtysevenList(); // [[69,37],{a:2}]
- var list3 = leadingThirtysevenList(1, 2, 3); // [[69,37],{a:2}, 1, 2, 3]
list 函数很简单,把传入的每个参数插入到一个数组里,我们用
给
- bind()
函数设置初始值,因为不用改变
- list
中
- list
的指向,所以直接传
- this
,从第二个参数开始,就是要传入
- undefined
函数的值,
- list
和
- list2
的返回值很好的说明了一切。
- list3
我自己一般使用的
的场景是配合
- bind()
函数,因为在执行
- setTimeout
时,
- setTimeout
会默认指向 window 对象,在使用
- this
之前,我是这么做的:
- bind()
- function Coder(name) {
- var that = this;
- that.name = name;
- that.getName = function() {
- console.log(that.name)
- };
- that.delayGetName = function() {
- setTimeout(that.getName,1000)
- };
- }
- var me = new Coder('Jins')
- me.delayGetName()//延迟一秒输出Jins
在函数内顶层定义一个 that 缓存
的指针,这样不论怎么调用,
- this
都是指向 Coder 的实例,但是多定义一个变量总是让人不太舒服。
- that
使用
就简单多了:
- bind()
- function Coder(name) {
- this.name = name;
- this.getName = function() {
- console.log(this.name)
- };
- this.delayGetName = function() {
- setTimeout(this.getName.bind(this),1000)
- };
- }
- var me = new Coder('Jins')
- me.delayGetName()//延迟一秒输出Jins
这样就 OK 了,直接把
的
- setTimeout
绑定到外层的
- this
,这肯定是我们想要的!
- this
最后附上参考地址:
Function.prototype.bind()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对 phperz 的支持。
来源: http://www.phperz.com/article/17/0529/329977.html