一、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()用参数列表。
三、参考文档
原文地址:https://cloud.tencent.com/developer/article/1922732
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。