Javascript/JQuery:为函数参数分配一整行代码

Javascript/JQuery: Assign a whole line of code to a function parameter?

本文关键字:分配 代码 参数 函数 JQuery Javascript      更新时间:2023-09-26

是否可以将整行代码分配给函数参数?举个例子:

function testFunc(parameter1){
    parameter1;
}
testFunc($(".someClass").text("someText"));

当函数与该参数一起使用时,parameter1是否可以被代码行替换?

我是JavaScript和jQuery的新手,所以我只是好奇这是否可能。我以前没有看到有人问过这样的问题。但如果有人问,请提供该问题的链接。感谢

听起来像是你在发明回调:)

传递一个实际函数,并用()调用它;

function testFunc(callback){
    callback();
}
testFunc(function(){$(".someClass").text("someText");});

是的,可以这样做,因为jQuery将对其进行评估并返回一个对象。

这里的关键见解是,函数可以像对待任何其他变量一样对待。

例如:

var i = 1;
var f = function() { console.log('hello!'); };

这里f是一个值,就像i一样,但您可以像调用任何其他函数一样调用:

f(); // prints 'hello!' in the console

因为它是一个值,所以可以将它传递给另一个函数:

function g(h) { h(); }
g(f); // prints 'hello!' in the console

花点时间确保您理解以上代码。我故意用模糊的名字,这样你就可以学习机械了。如果你有任何问题,请告诉我。

参数没有分配给函数,而是传递/发送/[在此处插入其他同义词]。

任何表达式(任何计算为某个值的代码)都可以传递。

在您的示例中,$(".someClass").text("someText")是一个计算为jQuery对象的表达式,因此您可以毫无疑问地将此代码单元用作函数的参数。

但是,如果您想传递一些必须作为现有函数过程的一部分执行的代码,则必须使用封装该行为的函数表达式。

例如

function executor(task) {
    task();
}

executor(function () {
    //code to be executed by the executor
});

是的,您可以像常规基元变量一样传递函数回调

在您的情况下,您应该在执行之前检查参数类型

function testFunc(parameter1){
    if(typeof parameter1==="undefined"){
       //arguments[0] will fall here
       console.log("No arguments case. parameter1 not defined")
    }
    else //function check 
    if(typeof parameter1==="function"){
       //you can parameter function here.
        return parameter1();
    }
    else{
        //regular case value or object, other than function types fall here
        console.log("not a function, received param type: "+ typeof(parameter1));
        return parameter1;
    }
}
$(function (){
    //let us say you have below vars
    var primitiveVar="test",
        fun = function(){console.log("function fun call")};
    //no args here
    testFunc();
    //sending primitiveVar
    testFunc(primitiveVar);
    //below is your call with jQuery Obj
    testFunc($(".someClass").text("someText"));
});