new function(){},Function,new Function()区别

本文介绍了JavaScript中四种不同的函数创建方式,包括普通函数声明、利用new Function构造函数、使用function关键字创建对象以及通过Function内置对象创建函数。每种方式都有其特点和适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数是JavaScript中很重要的一个语言元素,并且提供了一个[color=red]function关键字和内置对象Function[/color],下面是用法和它们之间区别。

使用方法一:
var foo01 = function() //or fun01 = function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

alert(typeof(foo01));
alert(foo01());

运行结果:
function
300
最普通的function使用方式,定一个JavaScript函数。两种写法表现出来的运行效果完全相同,唯一的区别是后一种写法有较高的初始化优先级。在大扩号内的变量作用域中,this指代foo01的所有者,即window对象。

使用方法二:
var foo02 = new function()
{
var temp = 100;
this.temp = 200;
return temp + this.temp;
}

alert(typeof(foo02));
alert(foo02.constructor());

运行结果:
object
300
这是一个比较puzzle的function的使用方式,好像是定一个函数。但是实际上这是定一个[color=red]JavaScript中的用户自定义对象[/color],不过这里是个匿名类。这个用法和函数本身的使用基本没有任何关系,在大扩号中会构建一个变量作用域,this指代这个作用域本身。
var obj = (new function(){
this.a = 123;
this.fn = function(e){alert(e)};
//return new String('123');
//return 123;
});
obj.fn(123);
可以理解返回一个对象。
(new function(){
return '123';
})

(new function(){
return new String('123');
}) 又有什么区别呐?


使用方法三:
var foo3 = new Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo3));
alert(foo3());

运行结果:
function
300
使用系统内置函数对象来构建一个函数,这和方法一中的第一种方式在效果和初始化优先级上都完全相同,就是函数体以字符串形式给出。

使用方法四:
var foo4 = Function('var temp = 100; this.temp = 200; return temp + this.temp;');
alert(typeof(foo4));
alert(foo4());

运行结果:
function
300

参考:

[url]http://www.jb51.net/article/13894.htm[/url]
[url]http://www.jb51.net/article/13895.htm[/url]
[url]http://www.planabc.net/2008/02/20/javascript_new_function/[/url]
[url]http://cykit.iteye.com/blog/72950[/url]
### JavaScript 中 `new Function` 的用法 在 JavaScript 中,`Function` 构造器可以用来动态创建函数。通过传递字符串形式的参数列表以及函数体来定义新的函数实例。这种方式虽然灵活,但在性能和安全性方面存在一些局限性。 以下是关于 `new Function` 的基本语法及其特点: #### 基本语法 ```javascript const myFunction = new Function([arg1, arg2, ...argN], functionBody); ``` - 参数 `[arg1, arg2, ..., argN]` 是可选的,表示新函数接受的参数名称。 - 参数 `functionBody` 表示实际执行的代码逻辑,作为字符串传入。 例如: ```javascript const sum = new Function('a', 'b', 'return a + b;'); console.log(sum(2, 3)); // 输出: 5 ``` 这种写法相当于声明了一个匿名函数并返回其结果[^1]。 #### 动态生成 UUID 示例 如果需要利用 `new Function` 来实现更复杂的场景,比如生成唯一的 ID 或者其他计算密集型操作,则可以通过如下方式完成: ```javascript // 使用 Math.uuid 方法生成唯一标识符 require('../tools/uuid'); const generateUniqueId = new Function('length', 'radix', ` const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""); let id = ""; for (let i = 0; i < length; ++i) { id += chars[Math.floor(Math.random() * radix)]; } return id; `); console.log(generateUniqueId(8, 16)); // 随机生成指定长度和基数的ID ``` 上述例子展示了如何借助 `new Function` 创建自定义功能模块,并结合外部工具库(如 uuid 工具)扩展应用范围[^3]。 #### 应用于银行业务模拟 考虑一个简单的银行账户管理系统案例,其中涉及到了存款、取款等功能需求。我们可以基于之前提到的知识点构建此类模型: ```javascript class BankAccount { constructor(balance = 0, limit = -100) { this.balance = balance; this.limit = limit; this.accountId = new Function('', 'return Math.uuid();')(); } deposit(amount) { if (amount > 0){ this.balance += amount; console.log(`Deposited ${amount}. New Balance:${this.balance}`); }else{ throw Error("Deposit must be positive"); } } withdraw(amount){ if ((this.balance - amount)>=this.limit && amount>0 ){ this.balance -= amount; console.log(`Withdrew ${amount}. Remaining Balance:${this.balance}`); }else{ throw Error("Insufficient funds or below allowed overdraft."); } } checkBalance(){ return this.balance; } } const account = new BankAccount(500,-200); account.deposit(100); try{account.withdraw(700);}catch(e){console.error(e.message)}; console.log(account.checkBalance()); ``` 这里我们还引入了 `Math.uuid()` 函数来自动生成每个用户的独立账号编号[^4]。 ### 注意事项 尽管 `new Function` 提供了一种强大的机制去处理那些无法预知结构的数据或者行为模式,但由于它依赖于解析字符串中的代码片段,在运行时可能会带来安全隐患同时也会影响程序效率。因此建议仅当确实必要时才采用这种方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值