2011-02-28 38 views
1
的片段

我的教授给我们的Javascript下面的代码片段,我们应该分析:了解的Javascript

function createMultiplyer(multiple) { 
n = multiple; 
return function(num) { 
return num * n; 
}; 
} 

var fiveMultiplyer = createMultiplyer(15); 
var x = fiveMultiplyer(10); 
alert(x); 
alert(fiveMultiplyer); 

这段代码输出包含文本“150”接着又警告读取警报function(num) { return num * n; }。但是,我似乎无法理解为什么是这样。

有人可以帮助我追踪代码并解释发生了什么吗?

回答

2

让我们考虑行

var fiveMultiplyer = createMultiplyer(15); 

它之后,fiveMultiplyer变量将有createMultiplyer函数的返回值(这是函数是如何工作)。这返回值是

function(num) { 
    return num * n; 
}; 

所以,代码类似这样(约n更高版本)

var fiveMultiplyer = function(num) { 
    return num * n; 
}; 

下一行是

var x = fiveMultiplyer(10); 

在这里我们只是调用上面的功能。它也使用变量n:该变量设置在createMultiplyer函数中:n = multiple;。因此,在我们的案例中,n15fiveMultiplyer(10)相当于10 * 15

就是这样。希望能帮助到你。

编辑
我还会注意到n是一个全局变量它声明的方式。所以,你可以从代码中的任何地方访问它。

0
var fiveMultiplyer = createMultiplyer(15); // Create a function that multiplies with 15 

此功能被当地人称为fiveMultiplier

var x = fiveMultiplyer(10); // Invoke the multiply-by-15 with argument 10 

结果在当地被称为x

alert(x); // 150 
alert(fiveMultiplyer); // The definition of multiply-by-15 as 
         // it is returned from createMultiplyer 

function createMultiplyer(multiple) { // Returns a new function which 
             // multiplies with "multiple" 
[var] n = multiple; // Note: "var" should have been used to keep "n" 
        // in scope (within "createMultiplyer"). 
return function(num) { // Return definition of multiplier function 
    return num * n; // "num" = arg. when invoked, "n" = multiplier at 
        // define time (when "createMultiplyer" was called) 
    }; 
} 
0

在JavaScript中,你可以有一个变量,它也起到一个功能的作用。

var fiveMultiplyer = createMultiplyer(15); 
    You are calling a CreateMultiplyer(15) function. 
    This function returns you another function and that is associated 
    with the fiveMultiplyer var. 
var x = fiveMultiplyer(10); 
    You are actually invoking the function which was returned in previous step. 
    hence evaluating the value to 10 * 15 = 150 
alert(x); 
    As explained this returns 150 
alert(fiveMultiplyer); 
    As explained this returns the complete function 
    returned by createMultiplyer(). 
0

想想它的最好方法是作为一个类或对象。 var fiveMultiplyer创建一个对象,该对象保存n = 15的值,并具有接受数字并将其乘以n的函数。

在Java中,这将是这个样子

public class Multiplyer { 
    private int n; 

    public Multiplyer(int n) { 
    this->n = n; 
    } 

    public int multiple (int m) { 
    return n*m; 
    } 
} 

Multiplyer myMultiplyer = new Multiplyer(15); 

System.out.println(myMultiplyer.multiple(10)); 

在JavaScript然而变量fiveMultiplye不必调用它的方法,您简单的通过它所需的变量并调用方法,并返回你。

希望有所帮助。