前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >详解JavaScript的Function对象

详解JavaScript的Function对象

原创
作者头像
Learn-anything.cn
发布2021-12-21 22:09:52
6000
发布2021-12-21 22:09:52
举报
文章被收录于专栏:learn-anything.cnlearn-anything.cn
一、Function 对象

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

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

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

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

代码语言:txt
复制
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()
代码语言:txt
复制
// 语法
function.call(thisArg, arg1, arg2, ...)
代码语言:txt
复制
// 使用方法
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()
代码语言:txt
复制
// 语法
func.apply(thisArg, [argsArray])
代码语言:txt
复制
// 使用方法
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()用参数列表。

三、参考文档

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、Function 对象
    • 1、函数是Function类型对象
      • 2、创建 函数
        • 3、Function 创建函数与 function 定义函数有什么不同?
        • 二、方法和属性
          • 1、Function.prototype.call()
            • 2、Function.prototype.apply()
            • 三、参考文档
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档