bind函数是复制函数,在复制函数的时候改变了this的指向
//语法:fun.bind(thisArg,args…)
function f1(x,y){console.log(x+y);console.log(this.age);}function Person(){this.age = 100;}var per = new Person();var ff = f1.bind(per,10,20); //这边将f1函数复制了一份,同时改变了f1函数中this的指向ff();

/
1.参数:
1.1 thisArg
当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用new 操作符调用绑定函数时,该参数无效。
1.2 arg1, arg2, …
当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法。
2.返回值:返回由指定的this值和初始化参数改造的原函数拷贝
/
示例1:对象方法中this的修改
function Person(age) {this.age=age;}Person.prototype.play=function () {console.log(this+"====>"+this.age);};function Student(age) {this.age=age;}var per=new Person(10);var stu=new Student(20);//复制了一份var ff=per.play.bind(stu);ff();

示例2:返回函数中this的修改
var x = 9;var module = {x: 81,getX: function() {return this.x;}};module.getX(); // 返回 81var retrieveX = module.getX;retrieveX(); // 返回 9, 在这种情况下,"this"指向全局作用域// 创建一个新函数,将"this"绑定到module对象// 新手可能会被全局的x变量和module里的属性x所迷惑var boundGetX = retrieveX.bind(module);boundGetX(); // 返回 81
示例3:定时器函数中this修改
<script>function ShowRandom() {}ShowRandom.prototype.showRandom = function(){//通过bind方法来修改定时器中this指向var timer = setInterval(function(){var num = this.produceNum();console.log(num);}.bind(this),1000)}ShowRandom.prototype.produceNum = function(){return parseInt(Math.random()*10+1);//1~10的随机数}var s = new ShowRandom();s.showRandom();</script>

