详解JavaScript的Function对象

371 阅读1分钟
一、Function 对象

Function 对象是全局对象,可以动态创建函数,实际上每个函数都是一个 Function 对象。

1、函数是Function类型对象
// 下面代码可以判断,函数是Function类型对象
(function(){}).constructor === Function // true
2、创建 函数
const sum = new Function('a', 'b', 'return a + b');

console.log(sum(2, 6));
// expected output: 8
3、Function 创建函数与 function 定义函数有什么不同?

由 Function 创建的函数不会创建当前环境的闭包,因此只能访问全局变量和自己的局部变量,不能访问 Function 创建函数时所在作用域的变量。

var x = 10;

function createFunction1() {
    var x = 20;
    return new Function('return x;'); // 这里的 x 指向最上面全局作用域内的 x
}

function createFunction2() {
    var x = 20;
    function f() {
        return x; // 这里的 x 指向上方本地作用域内的 x
    }
    return f;
}

var f1 = createFunction1();
console.log(f1());          // 10
var f2 = createFunction2();
console.log(f2());          // 20

二、方法和属性
1、Function.prototype.call()
  • 功能:用于调用其他函数。更多内容,看这里!

    // 语法
    function.call(thisArg, arg1, arg2, ...)
    
    // 使用方法
    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"
    
    

2、Function.prototype.apply()
  • 功能:用于调用其他函数。更多内容,看这里!

    // 语法
    func.apply(thisArg, [argsArray])
    
    // 使用方法
    const numbers = [5, 6, 2, 3, 7];
    const max = Math.max.apply(null, numbers);
    console.log(max);
    // expected output: 7
    
  • apply() 与 call() 的区别

    apply() 与 call() 功能是一样的,区别是提供参数的方式。apply()用数组作为参数;call()用参数列表。


三、参考文档