您好,我创建了一个自定义航点函数,该函数运行良好,但我希望能够向其添加函数。
这是工作的自定义航点函数:
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);
接下来我希望添加向 if 语句添加函数的功能,这是我想到的:
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 行添加了 functionName。然后我尝试在最后一行调用它。函数“test”没有触发,我收到错误:
未捕获的类型错误:functionName 不是函数。
谁能帮忙解决这个问题吗?
谢谢!
最佳答案
尝试使用 .call
或 .apply
( more 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)
。
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.
关于javascript - 添加将功能添加到现有自定义航点功能中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44551439/