Javascript私有方法专用调用方返回undefined

时间:2015-03-16 07:38:18

标签: javascript oop

我正在尝试定义方法_,以便我可以调用我的原型中定义的私有方法,例如http://webreflection.blogspot.hk/2008/04/natural-javascript-private-methods.html

我的功能很大,所以我只选择一个案例

XXXXX.prototype = (function(){

    var  privateMethod =function() {
       return "success";
    }

    //public method here
    return { //returns a prototyp
        constructor: XXXXX,

        pubMethod: function() {
            console.log("normal call",privateMethod.apply(this));//success
            console.log("_ call",this._(privateMethod)());//undefined
        },

        //private method dedicated caller
        _: function(fun) {
            var that = this;
            return function() {
                fun.apply(that, arguments);
            }
        }
    };
})()

问题:

为什么我的_没有按预期工作?我哪里错了?

1 个答案:

答案 0 :(得分:1)

您忘了在return

上添加fun.apply
function XXXXX(){}
XXXXX.prototype = (function(){    
    var  buildDimWhere =function() { return this.subject; }    
    return { 
        constructor: XXXXX,    
        pubMethod: function() {
            console.log(buildDimWhere.apply(this)) 
            console.log(this._(buildDimWhere)()) 
        },
        _: function(fun) {
            var that = this;
            return function() {
                return fun.apply(that, arguments); // <--- HERE!
            }
        }
    };
})()

// test code:
y = new XXXXX();
y.subject = '123'
y.pubMethod();

没有return就会给出:

{ subject: '123' }
123
{ subject: '123' }
undefined

添加return(参见<-- HERE!部分)后,输出:

{ subject: '123' }
123
{ subject: '123' }
123