arguments對象、apply()、匿名函數

在學習arguments對象時,碰到的一段code,不是太好理解。原文地址中文(http://www.jb51.net/article/25048.htm)、英文(http://www.sitepoint.com/arguments-a-javascript-oddity/)javascript

想要正確理解,須要把握紅色標註的地方。html

1,function.prototype.apply()用法java

2.須要明白majorTom在這裏指向了匿名函數function(){return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));}app

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        function format(string) {
            var args = arguments;
            var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
            return String(string).replace(pattern, function(match, index) {
                return args[index];
            });
        }
        function makeFunc() {
            var args = Array.prototype.slice.call(arguments);
            var func = args.shift();
            return function () {
                return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
            };
        }

        var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");
       console.log(majorTom("stepping through the door")) ;//majorTom是匿名函數的引用】

    </script>
</head>
<body>

</body>
</html>
相關文章
相關標籤/搜索