当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS中的bind()方法使用实例讲解

JS中的bind()方法使用实例讲解

2018年01月24日  | 移动技术网IT编程  | 我要评论
bind()方法

bind() 函数会创建一个新函数(称为绑定函数),当新函数被调用时 this 值绑定到 bind() 的第一个参数。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。

创建绑定函数

bind() 最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的 this 值。例如

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
偏函数(Partial Functions)

bind()的另一个最简单的用法是使一个函数拥有预设的初始参数。它们会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们的后面。

function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(undefined, 37);
var leadingThirtysevenListss = list.bind(undefined, 37,32,31,22);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
var list4 =leadingThirtysevenListss(); //[37,32,31,22]
var list5 = leadingThirtysevenListss(1, 2, 3); // [37,32,31,22, 1, 2, 3]
在定时器中使用

使用 window.setTimeout() 时,this 关键字会指向 window (或全局)对象。当使用类的方法时,需要 this 引用类的实例,你可能需要显式地把 this 绑定到回调函数以便继续使用实例。

function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
  window.setTimeout(this.declare.bind(this), 1000);//this指向LateBloomer对象 
};

LateBloomer.prototype.declare = function() {
  console.log('I am a beautiful flower with ' +
    this.petalCount + ' petals!');
};

var flower = new LateBloomer();
flower.bloom();  // 一秒钟后, 调用'declare'方法 
//I am a beautiful flower with 8 petals!
//如果不使用bind(this) 则 返回 I am a beautiful flower with undefined petals!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网