1

我只是想更好地理解/确认函数参数在这里看到的函数中:

function newFunction(data, status){

该函数会专门应用于数据和状态变量吗?

我不太明白这些论点是如何运作的。

4

3 回答 3

3

基本场景

定义函数时,该()区域用于输入。这些输入映射到发送的数据。

function newFunction(data, status){
}
newFunction(1,2);

在这种情况下,data将被赋予 的值1,并且status将被赋予 的值以2用于 的范围newFunction

不匹配的输入

但是,它并不总是直接映射。如果发送的参数较少,则未分配的输入变量变为undefined.

function newFunction(data, status){
}
newFunction(1);

在这种情况下,data将被赋予 的值1,并且status将被赋予 的值以undefined用于 的范围newFunction

参数对象

在 的范围内newFunction,还可以访问名为 的对象之类的数组arguments

function newFunction(data, status)
{
 var args = arguments;
}
newFunction(1);

在这种情况下,变量args将保存arguments对象。在那里您可以检查是否args.length只发送了 1 个参数。在这种情况下args[0],将为您提供该参数值。1

函数对象

一个函数可以用new关键字变成一个对象。通过new在函数上使用关键字,可以创建一个 Function 对象。一旦创建了 Function 对象,this就可以用来引用当前的 Function 对象而不是全局窗口。

function newFunction(data,status){
 if( this instanceof newFunction ){
  //use as a Function object
  this.data = data;
 }else{
  //use as a normal function
 }
}
var myNewFunction = new newFunction(1);

在这种情况下,myNewFunctionnow 持有对 Function 对象的引用,并且可以通过点表示法或索引作为对象访问。myNewFunction["data"]现在myNewFunction.data两者的值都为 1。

于 2013-01-08T23:46:00.360 回答
1

This means that the function accepts both data and status parameters. The programmer calling the funciton (you) is required for providing the parameters when calling the function (also known as arguments.)

Let's look at a simplified example:

function add(x, y) {
  return x + y;
}

The function here takes two numbers, adds them together, and returns the result. Now, as a programmer, you have the benefit of adding two numbers whenever you want without having to duplicate the functionality or copy/paste whenever you need your application to perform the same functionality.

Best of all, another programmer you work with can add two numbers together without worrying about how to do it, they can just call your function.

EDIT: Calling the function works as follows

var num1 = 10;
var num2 = 15;
var z = add(num1, num2); //z = 25
于 2013-01-08T23:38:47.583 回答
0
function newFunction(data, status){ ... function code ... }

这是一个名为 newFunction 的函数的 Javascript 定义。您可以将参数传递给函数。这些是变量,可以是数字或字符串,函数应该用它们来做某事。当然,函数的行为/输出取决于你给它的参数。

http://www.quirksmode.org/js/function.html

于 2013-01-08T23:57:59.273 回答