本文介绍了如何调用引用函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function wrapValue(n){

var localVariable = n;



return function(){return localVariable}

}



var wrap1 = wrapValue(5);

var wrap2 = wrapValue(10);



console.log(wrap1());



console.log(wrap2());



我尝试了什么:



我的猜测是wrap1是一个变量。 />


在console.log中,为什么要把它称为函数:wrap1()?



为什么不只是wrap1?

function wrapValue(n){
var localVariable = n;

return function () { return localVariable}
}

var wrap1 = wrapValue(5);
var wrap2 = wrapValue(10);

console.log (wrap1());

console.log(wrap2());

What I have tried:

my guess is that wrap1 is a variable.

In the console.log, why do you call it as a function: wrap1()?

why no just wrap1?

推荐答案

var wrap1 = wrapValue(5);

表示将 wrap1 分配给函数返回的某个对象 wrapValue 。那么,让我们看看这个函数返回什么。如您所见,它返回另一个函数。换句话说,返回的对象是函数函数对象。与其他对象不同,这种对象支持调用操作。语法 wrap1()只是语法调用。



问题为什么不只是wrap1?根本没有意义。 wrap1和wrap1()都是两个不同的表达式;两者都是正确的并返回完全不同的对象:首先返回函数调用的结果,如果此结果由 n 定义,则在调用 wrapValue ; second返回一个无参数函数函数对象,该函数对象又可以返回相同类型的对象。比较

means that wrap1 is assigned to some object returned by function wrapValue. So, let's see what this function returns. As you can see, it returns another function. In other words, returned object is a function function object. Unlike other objects, this kind of object supports the operation "call". And the syntax wrap1() is just the syntax call.

The question "why no just wrap1?" simply makes no sense. Both wrap1 and wrap1() are two different expressions; both are correct and return totally different objects: first return the result of the function call, the type if this result is defined by n passed during the call to wrapValue; second returns a parameterless function function object which, in turn, can return the object of the same type. Compare

var myObject = wrap1; // some parameterless function
var myOtherObject = wrap1(); // some object, same as n
// you can call
var someObject = myObject(); // because this is a function object
//someObject will be the same as myOtherObject



你明白了吗?



-SA


这篇关于如何调用引用函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 01:44