我们先来看一道题目
var write = document.write; write("hello"); //1.以上代码有什么问题 //2.正确操作是怎样的
不能正确执行,因为write函数丢掉了上下文,此时this的指向global或window对象,导致执行时提示非法调用异常,所以我们需要改变this的指向
正确的方案就是使用 bind/call/apply来改变this指向
bind方法
var write = document.write; write.bind(document)('hello');
call方法
var write = document.write; write.call(document,'hello');
apply方法
var write = document.write; write.apply(document,['hello']);
bind函数
bind()最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的this值。常见的错误就像上面的例子一样,将方法从对象中拿出来,然后调用,并且希望this指向原来的对象。如果不做特殊处理,一般会丢失原来的对象。使用bind()方法能够很漂亮的解决这个问题:
<script type="text/javascript"> this.num = 9; var module = { num: 81, getNum: function(){ console.log(this.num); } }; module.getNum(); // 81 ,this->module var getNum = module.getNum; getNum(); // 9, this->window or global var boundGetNum = getNum.bind(module); boundGetNum(); // 81,this->module </script>
偏函数(Partial Functions)
Partial Functions也叫Partial Applications,这里截取一段关于偏函数的定义:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
这是一个很好的特性,使用bind()我们设定函数的预定义参数,然后调用的时候传入其他参数即可:
<script type="text/javascript"> function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); console.log(list1);// [1, 2, 3] // 预定义参数37 var leadingThirtysevenList = list.bind(undefined, 37); var list2 = leadingThirtysevenList(); console.log(list2);// [37] var list3 = leadingThirtysevenList(1, 2, 3); console.log(list3);// [37, 1, 2, 3] </script>
和setTimeout or setInterval一起使用
一般情况下setTimeout()的this指向window或global对象。当使用类的方法时需要this指向类实例,就可以使用bind()将this绑定到回调函数来管理实例。
<script type="text/javascript"> function Bloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } // 1秒后调用declare函数 Bloomer.prototype.bloom = function() { window.setTimeout(this.declare.bind(this), 1000); }; Bloomer.prototype.declare = function() { console.log('我有 ' + this.petalCount + ' 朵花瓣!'); }; var test = new Bloomer(); test.bloom(); </script>
新闻热点
疑难解答
图片精选