猿问

javascript如何解析参数?

我刚接触JavaScript并来自不同的编程背景,我很难理解如何JavaScript解析传递给函数的参数。


让我们看一个简单的例子。从jQuery 的文档中.on,我看到了 2 个不同的签名:


.on( 事件 [, 选择器 ] [, 数据 ], 处理程序 )


.on( 事件 [, 选择器 ] [, 数据 ] )


但是,以下代码段会生成完全有效的代码并执行预期的操作:


$(function() {

  let dat = {a: 1, b: 2}

  $('#do').on('click', dat, function(evt) {

    alert(evt.data.b);

  });

  $('#do2').on('click', function(evt) {

    alert("click");

  });

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="do">

  Click!

</button>

<button id="do2">

  Click!

</button>

如何JavaScript“知道”dat在第一种情况下是数据(而不是selector)?显然两个签名都没有位置匹配?那么它在内部是如何工作的,我如何将这种模式用于我自己的功能呢?


扬帆大鱼
浏览 215回答 3
3回答

qq_花开花谢_0

查看jQuery 源代码on,手动检查类型并手动计算任何省略的参数(参数始终从左到右填充):function on( elem, types, selector, data, fn, one ) {&nbsp; &nbsp; var origFn, type;&nbsp; &nbsp; // Types can be a map of types/handlers&nbsp; &nbsp; if ( typeof types === "object" ) {&nbsp; &nbsp; &nbsp; &nbsp; // ( types-Object, selector, data )&nbsp; &nbsp; &nbsp; &nbsp; if ( typeof selector !== "string" ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ( types-Object, data )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data = data || selector;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selector = undefined;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for ( type in types ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; on( elem, type, selector, data, types[ type ], one );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return elem;&nbsp; &nbsp; }&nbsp; &nbsp; if ( data == null && fn == null ) {&nbsp; &nbsp; &nbsp; &nbsp; // ( types, fn )&nbsp; &nbsp; &nbsp; &nbsp; fn = selector;&nbsp; &nbsp; &nbsp; &nbsp; data = selector = undefined;&nbsp; &nbsp; } else if ( fn == null ) {&nbsp; &nbsp; &nbsp; &nbsp; if ( typeof selector === "string" ) {...等等。来自非动态类型的背景可能会令人震惊,但这在 JS 中很常见。

一只名叫tom的猫

如何JavaScript“知道”dat在第一种情况下是数据(而不是selector)?它没有。事实上,javascript 中的函数不需要显式声明它们的参数。每个函数都可以访问一个被调用的对象,该对象arguments保存(你可能已经猜到)所有传递给函数的参数。因此,该函数只需查看此对象即可找出传递给它的所有参数。function foo() {&nbsp; &nbsp; console.log(arguments);}foo(1, 2, 3, 4);那么它在内部是如何工作的,我如何将这种模式用于我自己的功能呢?我相信我已经解释了它是如何工作的,但我的建议是不要将这种模式用于你自己的函数。如果可以,我什至建议不要编写普通的 javascript。有许多可用语言的超集,使您可以更明确地使用函数接受的类型和参数。Typescript是一种这样的语言,它在编写 javascript 时引入了急需的类型安全。scala.js如果你喜欢那种东西,你也可以试试。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答