是否有必要在JS中使用参数向函数添加参数

如何解决是否有必要在JS中使用参数向函数添加参数

来自Java并尝试学习Javascript,以下代码有效:

0.1e1

而以下内容并没有给出错误

const myCustomDiv = document.createElement('div');

function respondToTheClick(evt) {
    evt.target.textContent = 'This paragraph has been clicked!'; 
}

for (let i = 0; i < 100; i++) {
    const newElement = document.createElement('p');
    newElement.textContent = 'This is paragraph number ' + i;

    myCustomDiv.appendChild(newElement); 
}

document.body.appendChild(myCustomDiv);

myCustomDiv.addEventListener('click',respondToTheClick);

产生的错误是:

参数类型void无法分配给参数类型(this:HTMLDivElement,ev:HTMLElementEventMap [string])=>任意

对于Java,如果方法需要参数,则必须提供该参数。 JS不是这种情况吗-如果是这样,它如何工作?还是只有事件监听器才是这种情况?

解决方法

在JavaScript中,函数是一流的对象。您可以对可以对对象执行的功能执行任何操作。这包括将其作为函数的参数传递。

addEventListener("click",respondToTheClick)

…将respondToTheClick传递为addEventListener的第二个参数。

addEventListener('click',respondToTheClick(event) );

等效于:

let return_value = respondToTheClick(event);
addEventListener('click',return_value);

addEventListener的第二个参数必须是一个函数。 respondToTheClick(event)的返回值不是函数。这就是为什么您会得到一个错误。

当浏览器中内置的其他代码以及addEventListener函数内部调用作为参数传递给您的函数时,那个代码将向其传递Event对象,例如一个论点。

function handleEvent(e) {
    console.log(e);
}

function addEventDemo(event_type,event_handler) {
    event_handler("E is " + event_type);
}

addEventDemo("click",handleEvent);


也就是说,即使将JS设置为将参数分配给变量,JS也不要求您将其传递给函数。您未定义的任何值都将获得值undefined

function foo(a,b,c,d) {
    console.log({ a,d });
}

foo(1,2);

但是,尽管JS不需要它,但是函数可以强制执行某些事情。

function foo(a,d) {
    if (typeof a !== "number") throw "a is not a number";
    if (typeof b !== "number") throw "b is not a number";
    if (typeof c !== "number") throw "c is not a number";
    if (typeof d !== "number") throw "d is not a number";
    console.log({ a,2);

,

第一个示例是将对函数respondToTheClick的引用传递给addEventListener。该功能不会立即执行,而是会在事件发生时注册(使用addEventListener由浏览器执行。这在javascript中称为callback function

在第二个示例中,您要调用该函数,然后将该调用的返回值作为参数传递给addEventListener。例如,foo(sum(1,2))会将3传递给foo,而不是函数sum本身。

在javascript中,函数是对象,可以像使用常规对象一样精确地使用它们。它们也是可调用的(可以被调用)。与Java中一样,在javascript中,您可以将对象分配给不同的变量,这样将不会创建该对象的新副本,而是会创建指向同一对象的不同变量。由于函数是javascript中的对象,因此以下内容有效且可以正常工作:

function sayHi() {
  console.log("Hi");
}

// 'func' and 'sayHi' will point to the same object,the object being
// a function that prints "Hi" to the console. 
var func = sayHi;  


// although there was never a function defined called 'func',this
// will still work because of the above assignment
func();

现在,这正是问题的第一个示例中发生的情况,但是没有将函数respondToTheClick分配给变量,而是将其作为参数传递给addEventListener。从addEventListener调用参数类似于从上例中调用变量func;它将执行功能。这就是javascript中使用的回调。

在Java中,最接近回调的是使用Method反射,如下所示:

public class SomeClass {
    public void sayHi(String name) {
        System.out.println("Hi " + name);
    }
}

/////////////////////////////////////////////////////////////////////////////

public class Example {
    public static void main(String[] args) {
        // get a reference to a method called 'sayHi' on the class 'SomeClass' that
        // has only one parameter of type String,we have to specify the type of
        // parameters because of method overloading (different methods can have the
        // same name in java and we distinguish between them using their parameters).
        // In javascript this can be done by a simple assignment,but again,that's javascript.
        Method theSayHiMethod = SomeClass.class.getMethod("sayHi",String.class);

        SomeClass inst = new SomeClass();

        // now we can pass the reference to 'sayHi' (or more accurately,its reflection)
        // without invoking it. Notice how 'addEventListener("click",respondToTheClick)'
        // is the same as:
        callAMethodOnObject(inst,theSayHiMethod);
    }

    public static void callAMethodOnObject(Object object,Method method) {
        // 'sayHi','theSayHiMethod' and 'method' are the exact same method,the latter
        // two are reflections. Invoking the reflections will execute the function
        // they reflect as if it was called directly. Since everything in java is
        // an instance of some class (there are no standalone functions),we have to
        // specify the context for the method,in this example it is 'object' which is
        // the an instance of 'SomeClass' where 'sayHi' is defined
        method.invoke(object,"World!");
    }
}

这在Java中几乎从未使用过,因为如果您希望在发生某事(例如事件)时要调用一个方法,通常会传递包含该方法的整个对象,并且该对象将被调用直接在传递的对象上调用它,就像这样:

class MyClickHandler implements ClickHandler {
    public void onClick(Event event) {
        // ...
    }
}

// then pass it to another method like so:

ClickHandler handler = new MyClickHandler();
someObject.setClickListener(handler);

// when a click happens,the method 'onClick' of 'handler' will be called. Javascript
// has the ability to pass the function directly without the need to wrap it in an
// object first.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-