bind功能特性
- bind方法创建一个新函数,改变函数的作用域,并且不同于call、apply,函数不执行
- bind可用于实现偏函数,则实现时需要同时保存bind()被传入的参数arguments以及返回的新创建函数被传入的参数arguments
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 list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
3.bind用于构造函数时候this作用域改变无效,核心点是在继承原函数的原形__proto__的时候增加一个fNOP父类,即 原型链继承方式 来判断原函数是否是new的构造函数,只有构造函数返回的对象才可以继承原型链
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
return this.x + ',' + this.y;
};