Javascript重新定义私有函数

时间:2014-09-21 10:01:05

标签: javascript

我想建立一个类似于jQuery的简单对象,但我不知道如何在对象内部重新定义一个函数。

如何在ZOO对象之外重新创建自定义errorHandler,或者我是以错误的方式进行此操作;我读原型可能是一个更好的方法,但话说回来,我只定义了一次对象。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
        (function( $ ) {
            var hasError = 0;

            var errorHandler = function(msg) {
                hasError = 1;
                console.log('Before: ' + msg);
            };

            var callback = {
                success: function(data) { },
                failure: function(msg) { }
            };

            $.init = function() {
                try {
                    something_bad;
                }
                catch(e) {
                    errorHandler(e.toString());
                }
                callback.success(1);
            };

            $.override = function(methodName, method) {
                // How do i redefine the method??
                methodName = method;
            };

        }(window.ZOO = window.ZOO || {}));
    </script>
</head>

<body>
<script>
    ZOO.override('errorHandler', function(msg) {
        hasError = 1;
        console.log('After: ' + msg);
    });

    ZOO.override('callback.success', function(data) {
        console.log(data);
    });

    ZOO.init();
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

私有函数的this上下文为window。似乎创建了一些内部函数变量,我们可以使用函数名作为变量:

 $.override = function(methodName, method) {
     errorHandler = method;
 };

正如T.J.Crowder所建议的那样,你应该定义一个这样的函数变量:

var errorHandler = function(msg) { ... }

更新:要使其动态化,您可以使用eval()这样的功能:

$.override = function(methodName, method) {
     eval(methodName + " = method");
};

答案 1 :(得分:0)

我会选择protoryping: 查看this fiddle is for you!

实现:

function ZOOd (){ 
    this.hasError= 0;
} 

ZOOd.prototype.errorHandler = function(msg){ 
    this.hasError = 1;
    console.log('Before: ' + msg);
} 

ZOOd.prototype.init =function(){ 
    try {
        /*something_bad;*/
    }
    catch(e) {
        this.errorHandler(e.toString());
    }
} 



ZOO.prototype = new ZOOd();        // Here's where the inheritance occurs 
ZOO.prototype.constructor=ZOO;       // Otherwise instances of ZOO would have a constructor of ZOO 

function ZOO(){ 
    this.hasError= 0;
} 
ZOO.prototype.errorHandler = function(msg){ 
    this.hasError = 1;
    console.log('After: ' + msg);
} 

var zoo = new ZOO();
zoo.init();

我希望这有帮助!