JS bind 函数

来源:互联网 发布:5230软件下载 编辑:程序博客网 时间:2024/04/30 08:30

bind 函数

bind 函数的作用是改变this的指向。(这里说的bind 不是jq的bind 函数。)
举个栗子:

var name = "outerName";let obj = {    name: "innerName",    getName: function () {        return function () {            return this.name;        }    }};obj.getName()();   //"outerName"

(小提示: 这里的全局变量为什么不能用let: let 定义的变量不是全局变量,而调用函数时this指向全局window 。至于为什么可以看这里)

这里有2个解决方案:
1.在getName中定义一个 that 保存this .

 getName: function () {    let that = this;        return function () {            return that.name;        }    }

2.使用apply或者call方法指定函数的作用域:

var name = "outerName";let obj = {    name: "innerName",    getName: function () {        return function () {            return this.name;        }    }};let func = obj.getName();alert(func.apply(obj))   //"innerName"

ES5 提供了新的bind方法可以更简介明朗的实现这种效果:

var name = "outerName";let obj = {    name: "innerName",    getName: function () {        return function () {            return this.name;        }    }};let func = obj.getName();func = func.bind(obj);alert(func())   //"innerName"

对于少数浏览器不支持bind函数的兼容性操作:

Function.prototype.bind=Function.prototype.bind||    function(context){        var self=this;        return function()        {            return self.apply(context,arguments);        }    }

参考自:http://www.cnblogs.com/GongQi/p/4041460.html