简体   繁体   中英

Why am I getting undefined on this module pattern in javascript?

Why am I getting undefined on the x.test()? It's an anonymous function.

var Calculator = function () {    
  // private stuff
  var x = 55;      
  return {
    // public members    
    y: x,
    test: function () {
      console.log(x);
    }
  };
}; 

var x = new Calculator(); 

console.log(x.y);
console.log(x.test());

You're logging the return value of x.test which is implicitly undefined :

console.log(x.y); // Logs 55
var x = x.test(); // Logs 55 (because of the console.log call in x.test)
console.log(x); // Logs undefined (because that's what x.test returned)

Did you mean to return the "private" x from the test method?

// ...
return {
    y: x,
    test: function () {
        return x;
    }
}

Because you are printing ( console.log ) the return of a function that doesn't return anything.

Just return the x value in your test function:

var Calculator = function () {
    // private stuff
    var x = 55;

    return {
        // public members
        y: x,
        test: function () {
            return x;
        }
    };
}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM