添加将函数添加到现有自定义 waypoints 函数中的功能

Add ability to add function into an existing custom waypoints function

您好,我创建了一个自定义航路点功能,效果很好,但我希望能够向其添加功能。

这是有效的自定义航路点函数:

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).

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.