我只是想更好地理解/确认函数参数在这里看到的函数中:
function newFunction(data, status){
该函数会专门应用于数据和状态变量吗?
我不太明白这些论点是如何运作的。
我只是想更好地理解/确认函数参数在这里看到的函数中:
function newFunction(data, status){
该函数会专门应用于数据和状态变量吗?
我不太明白这些论点是如何运作的。
基本场景
定义函数时,该()
区域用于输入。这些输入映射到发送的数据。
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);
在这种情况下,myNewFunction
now 持有对 Function 对象的引用,并且可以通过点表示法或索引作为对象访问。myNewFunction["data"]
现在myNewFunction.data
两者的值都为 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
function newFunction(data, status){ ... function code ... }
这是一个名为 newFunction 的函数的 Javascript 定义。您可以将参数传递给函数。这些是变量,可以是数字或字符串,函数应该用它们来做某事。当然,函数的行为/输出取决于你给它的参数。