Javascript以下代码行之间有什么区别

时间:2018-02-20 07:12:33

标签: javascript jquery

以下代码行之间有什么区别,当我们使用jquery时。是否有更优先的人?

<script>
alert("hello");  // 1. alert hello 
$(function(){alert("hello");}); // 2. Also alert hello
(function($){alert("hello");})(jQuery); // 3. It also alert hello
</script>

1 个答案:

答案 0 :(得分:1)

  • 在第一行中,您只是致电alert()

  • 在第二行中,您尝试获取一组匹配的元素,这些元素可以在DOM中根据传递的参数找到,也可以通过传递HTML字符串(more here)来创建。因此,评估参数并调用alert()

  • 在第三行中,您正在调用自调用函数并将jQuery作为参数传递但不使用它。并调用alert()

总结

第一行alert("hello");绝对是最好的,因为最后两行导致无用的计算只是为了提醒。