2012-11-22 52 views
1

JavaScript函數如何在以下程序中使用原型函數name.argument進行調用?JavaScript函數如何調用原型函數name.argument的工作?

function getLAdd() { 
    // this sets all the variables containing positions of ball and bar with their respective ids. 
    var ladd = 0; 
    var pball = $("#ball"); 
    var pbar = $("#bar"); 
    var bar_position = pbar.position(); 
    var ball_position = pball.position(); 
    if (ball_position.top >= window.innerHeight - 100) { 
     if (ball_position.left - 10 >= bar_position.left && ball_position.left - 10 <= bar_position.left + 100) { 
      ladd = -2; 
     } 
     if (ball_position.left + 10 <= bar_position.left + 200 && ball_position.left + 10 >= bar_position.left + 100) { 
      ladd = 2; 
     } 
    } 
// how does getLAdd.ladd work ? Is this a type of dynamic call ? 
    if (ladd == 0) { 
     ladd = getLAdd.ladd; 
    } 
    if (ball_position.left <= 15 || ball_position.left >= window.innerWidth - 40) 
     ladd = -ladd; 

    getLAdd.ladd = ladd; 
    return ladd; 
} 

回答

3

JavaScript中的函數是對象,因此您可以爲它們添加屬性。

在此代碼名爲ladd屬性已被添加到getLAdd函數,並在此線正被檢索到:

ladd = getLAdd.ladd; 

並在此行被更新:

getLAdd.ladd = ladd; 

你可以用任何函數做同樣的事情。

function f() { 
     // get the property 
    console.log(f.foo); // bar 
} 

    // add a property to the function object 
f.foo = "bar"; 

    // get the property 
console.log(f.foo); // bar 

    // call the function 
f();