2017-06-14 60 views
0

您好我已經創建了一個自定義的航點功能,該功能運行良好,但我希望能夠向其中添加功能。添加將功能添加到現有自定義航點功能中的功能

這裏是工作的自定義航點功能:

function createWaypoint (triggerElementId, animatedElement, className, offsetVal) { 
    var waypoint = new Waypoint({ 
     element: document.getElementById(triggerElementId), 
     handler: function(direction) { 
      if (direction === 'down') { 
       jQuery(animatedElement).addClass(className); 
       this.destroy(); 
      } 
     }, 
     offset: offsetVal 
    }); 
} 

//Waypoint Instances 
createWaypoint("x", ".y", "z", 500); 

接下來我想添加到一個函數添加到的能力,如果聲明,這裏是我想出了:

function createWaypoint (triggerElementId, animatedElement, className, offsetVal, functionName) { 
    var waypoint = new Waypoint({ 
     element: document.getElementById(triggerElementId), 
     handler: function(direction) { 
      if (direction === 'down') { 
       jQuery(animatedElement).addClass(className); 
       functionName(); 
       this.destroy(); 
      } 
     }, 
     offset: offsetVal 
    }); 
} 

function test() { 
    alert('Hello World'); 
} 

//Waypoint Instances 
createWaypoint("x", ".y", "z", 500); 
createWaypoint("x", null, null, null, test); 

我在第1行和第7行添加了函數名。然後我試圖在最後一行調用它。函數「測試」不觸發,我得到的錯誤:

未捕獲TypeError:functionName不是一個函數。

任何人都可以幫忙嗎?

謝謝!

回答

1

嘗試對.call.applymore about them two):

function createWaypoint (triggerElementId, animatedElement, className, offsetVal, functionName) { 
    var waypoint = new Waypoint({ 
     element: document.getElementById(triggerElementId), 
     handler: function(direction) { 
      if (direction === 'down') { 
       jQuery(animatedElement).addClass(className); 

       if(typeof functionName === 'function') { 
        functionName.call(); 
       } else { 
        console.log('functionName parameter is not a function.'); 
       } 

       this.destroy(); 
      } 
     }, 
     offset: offsetVal 
    }); 
} 

function test() { 
    alert('Hello World'); 
} 

//Waypoint Instances 
createWaypoint("x", ".y", "z", 500); 
createWaypoint("x", null, null, null, test); 

編輯:其實,你應該使用functionName.call(undefined)或從你的慾望的函數的範圍傳遞this參數。它可以來自handler函數的回調,也可以來自createWaypoint,即。 functionName.call(this)functionName.call(mappedThis)

由於MDN documentation狀態:

thisArg — The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode , null and undefined will be replaced with the global object and primitive values will be converted to objects.

+0

是的!這工作完美。謝謝先生 –

+1

沒問題。我已經更新了我的答案。請閱讀。 – omerowitz

+0

所以基本上只是將'functionName.call();'改爲'functionName.call(this);'? @omerowitz –