Function(翻译自mozilla developer network)

来源:互联网 发布:淘宝卖家创业故事 编辑:程序博客网 时间:2024/05/25 19:57

Function

javascript的函数都是Function对象实例。

Syntax

new Function ([arg1[, arg2[, ...argN]],] functionBody)

parameters

arg1, arg2, … argN

函数的参数名。每一个都必须是字符串,且必须是合法的javascript变量名或者以逗号’,’分隔。
例如’a’,’b’或者’a,b’

functionBody

包含javascript语句,称为函数定义。

Description

使用new Function()或者Function()创建函数,比使用function关键字要低效。

Function prototype object

properties

Function.arguments

已经被弃用,直接在函数体里面使用arguments即可。

Function.length

函数期望的参数数量,由声明函数时,函数参数个数决定。

Function.name

函数名。

Method

Function.prototype.apply()

调用函数,并更改调用时的this为指定的value,参数通过array或者array-like进行传递。

Function.prototype.bind()

返回创建的一个新的函数。它被调用时,this为指定的value。并且,当它被调用时会有预先提供的函数参数传入。

Function.prototype.call()

调用函数,并更改调用时的this为指定的value,参数按顺序传递。

Function.prototype.toString()

返回函数的源代码,重写了Object.prototype.toString()方法。

Examples

// Example can be run directly in your JavaScript console// Create a function that takes two arguments and returns the sum of those argumentsvar adder = new Function('a', 'b', 'return a + b');// Call the functionadder(2, 6);// > 8

Difference between Function constructor and function declaration

采用Function constructor创建的函数不会在creation context创建closure。
因此,采用Function constructor创建的函数,它们总是在全局作用域下,它们只能访问到自己内部的变量和全局变量。

0 0