看似无参却有参-----JS中的函数传参

事件event

JS的事件event是一个非常大的对象,不管是什么事件,事件的详情都会绑定到全局变量event中。这样做之所以安全,就是因为JS是单线程的。

<html>

<body>
    <h1>天下大势为我所控</h1>
</body>
<script>
    function $() {
        if (arguments.length == 1 && arguments[0].constructor.name === "String") {
            return document.querySelector(arguments[0]) //这里使用arguments传递参数
        } else {
            alert("what are you doing ")
        }
    }

    $("h1").onclick = function() {
        console.log(event)
    }
</script>

</html>

函数参数arguments

function f() {
    console.log(arguments)
}
f(1, 2, 3, "one", { name: 'w', age: 1 })

复制这段代码,F12打开浏览器控制台,粘贴运行即可看到结果。
arguments是一个数组的派生类,它比数组多了一个callee属性。

arguments参数像event参数一样,也是一个全局变量,每次函数的入栈、弹栈操作都会更新arguments参数,所以arguments参数是存储在栈里面的。

获取当前函数名称

给函数的祖先Function绑定一个getName函数。

Function.prototype.getName=function(){
    return this.name
    //如果不嫌麻烦,还可以使用正则表达式从整个函数(包括函数体)中抽取函数名称
    // this.toString().match(/functions*([^(]*)(/)[1]
}
function f(){}
f.getName()

还可以使用arguments中的callee对象来获取函数名称。

前端是一门需要积累的技术,不懂后端的算法工程师不是好前端。

原文地址:https://www.cnblogs.com/weiyinfu/p/7828510.html