Function 构造函数,apply,call,bind

Function 构造函数 创建一个新的Function对象。

在 JavaScript 中, 每个函数实际上都是一个Function对象。

var sum = new Function('a', 'b', 'return a + b');  
//使用Function构造器生成的Function对象是在函数创建时解析的。
//这比你使用函数声明或者函数表达式(function)并在你的代码中调用更为低效,因为使用后者创建的函数是跟其他代码一起解析的。 
console.log(sum(2, 6)); 
// expected output: 8

属性

Function.arguments 
以数组形式获取传入函数的所有参数。此属性已被arguments替代。
Function.arity 
用于指定的函数的参数的个数,但已被删除。使用length属性代替。
Function.caller 
获取调用函数的具体对象。
Function.length
获取函数的接收参数个数。
Function.name 
获取函数的名称。
Function.displayName 
获取函数的display name。
Function.prototype.constructor
声明函数的原型构造方法,详细请参考 Object.constructor 。

方法

Function.prototype.apply()
在一个对象的上下文中应用另一个对象的方法;参数能够以数组形式传入。
Function.prototype.call()
在一个对象的上下文中应用另一个对象的方法;参数能够以列表形式传入。

 

Function.prototype.bind()
bind()方法会创建一个新函数,称为绑定函数.
当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind()方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.
Function.prototype.isGenerator() 
若函数对象为generator,返回true,反之返回 false
Function.prototype.toSource() 
获取函数的实现源码的字符串。 覆盖了 Object.prototype.toSource 方法。
Function.prototype.toString()
获取函数的实现源码的字符串。覆盖了 Object.prototype.toString 方法。

备注:

call()方法的作用和 apply() 方法类似,

区别就是call()方法接受的是参数列表

而apply()方法接受的是一个参数数组

thisArg调用绑定函数时作为this参数传递给目标函数的值。

func.call(thisArg, arg1, arg2, ...)
func.apply(thisArg, [argsArray])
function Product(name, price) {
  this.name = name;
  this.price = price;
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

console.log(new Food('cheese', 5).name);
// expected output: "cheese"
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); 
// ["a", "b", 0, 1, 2]
func.bind(thisArg[, arg1[, arg2[, ...]]])
var module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

var unboundGetX = module.getX;
console.log(unboundGetX()); // this是全局作用域
// expected output: undefined

var boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
 this.x = 9;    // 全局x定义
 const module = {
   x: 81,
   getX: function() { return this.x; }
 };
 module.getX();
 //  81

 const retrieveX = module.getX;
 retrieveX();
 //  9; 此时retrieveX的this是window

 // bind 绑定 module 之后,this指向 module
 const boundGetX = retrieveX.bind(module);
 boundGetX();
 //  81