如何获得传递参数?

时间:2014-08-24 14:20:57

标签: javascript jquery

我有以下脚本,我无法在函数('hello')上传递参数。

我的代码中出错了什么?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Fabric</title>
    <style>
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        Snip = function () {
        };
        Snip.prototype.methodB = function () {
            alert('do smt');
        };
        Snip_Nav = (function (Snip) {
            var args = arguments[0]; // problem here
            var Snip_Nav = function () {
                this.config = {
                    name: args
                };
            };
            $.extend(true, Snip_Nav.prototype, Snip.prototype, {
                init: function () {
                    this.items = ['red', 'blue', 'yellow'];
                },
                methodA: function () {
                    alert(this.config.name);
                }

            });

            return Snip_Nav;

        })(Snip);

        function start() {
            var test1 = new Snip_Nav('hello');
            var test2 = new Snip_Nav();
            test1.methodA();
            test2.methodA();
        };
    </script>
</head>
<body onload="start();">

</body>
</html>

2 个答案:

答案 0 :(得分:1)

代码的问题在于执行IIFE后,Snip_Nav的值是函数:

function () {
   this.config = {
      name: args
  };
};

这不是你所期望的。

一个非常简单的修复(但可能会导致其他问题,具体取决于您的整个代码),可能会有:

function (myArg) {
   this.config = {
      name: myArg
  };
};

答案 1 :(得分:1)

您必须获得第二 arguments定义的Snip_Nav

Snip_Nav = (function (Snip) {
    var Snip_Nav = function () {
        var args = arguments[0]; // problem SOLVED here
        this.config = {
            name: args
        };
    };
    ...
相关问题