JaskeyLam
JaskeyLam

Reputation: 15755

Javascript private method dedicated caller returns undefined

I am trying to defined a method _ so that I can call my private method defined in my prototype, like http://webreflection.blogspot.hk/2008/04/natural-javascript-private-methods.html

My function are huge so I just pick a piece of case here

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);
            }
        }
    };
})()

Problem:

Why my _ is not working as expected?where am I wrong?

Upvotes: 1

Views: 156

Answers (1)

Kokizzu
Kokizzu

Reputation: 26848

You forgot to add return on the 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();

Without return it gives:

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

After adding return (see <-- HERE! part), the output:

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

Upvotes: 1

Related Questions