对bind的总结

语法:

bind() 方法的主要作用就是将函数绑定至某个对象,bind() 方法会创建一个函数,函数体内this对象的值会被绑定到传入bind() 函数的值。

bind的定义: 

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。

实现对象继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var A = function(name) {
 this.name = name;
}
 
var B = function() {
 A.bind(this, arguments);
}
 
B.prototype.getName = function() {
 return this.name;
}
 
var b = new B("hello");
console.log(b.getName()); // "hello"

 

bind()的兼容性写法

1
2
3
4
5
6
7
8
9
10
11
12
if (!Function.prototype.bind) {
 Function.prototype.bind = function() {
  var self = this, // 保存原函数
   context = [].shift.call(arguments), // 需要绑定的this上下文
   args = [].slice.call(arguments); // 剩余的参数转成数组
  return function() { // 返回一个新函数
   // 执行新函数时,将传入的上下文context作为新函数的this
   // 并且组合两次分别传入的参数,作为新函数的参数
   return self.apply(context, [].concat.call(args, [].slice.call(arguments)));
  }
 };
}

bind与 call/apply方法的区别

共同点:

都可以改变函数执行的上下文环境;

不同点:

bind: 不立即执行函数,一般用在异步调用和事件; call/apply: 立即执行函数。

posted @ 2020-12-20 20:14  混混子  阅读(158)  评论(0)    收藏  举报