如何解决是否有必要在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 举报,一经查实,本站将立刻删除。