Modular Design Pattern - YDKJS - confused about adding a prototype

Modular Design Pattern - YDKJS - confused about adding a prototype
0

#1

I read chapter 2 of YDKJS Up & Going and understand how the following example works.

function User(){
  var username, password;
  function doLogin(user,pw) {
    username = user;
    password = pw;
   // do the rest of the login work
  }
  var publicAPI = { login: doLogin };
  return publicAPI;
}

// create a `User` module instance
var fred = User();
fred.login( "fred", "12Battery34!" );

What I don’t understand is how to use a prototype for doLogin such as what I am trying to do below. Can someone explain what I would need to modify in the User function to make it work? I tried using this.doLogin also in publicAPI but that did not work either.

function User(){
  var publicAPI = { login: doLogin };
  return publicAPI;
}
User.prototype.doLogin = function(user,pw) {
  this.username = user;
  this.password = pw;
  // do the rest of the login work
}

// create a `User` module instance
var fred = User();
fred.login( "fred", "12Battery34!" );

#2

publicAPI (the object returned by a call to User()), is not related to User.prototype. Also, doLogin is not within scope of the User function.

This seems to work, but it looks clumsy

function User() {
  var publicAPI = { login: User.prototype.doLogin };
  return publicAPI;
}
User.prototype.doLogin = function(...) {...}

The next book will explain prototypes :wink:


#3

If you put the username and password in a prototype method, they are accessible - fred.username, fred.password.
The way it’s done in the book, those values are private from being assigned locally within the function and due to the closure can be accessed from the enclosed function doLogin. When you invoke User it returns an object with a property login that’s value is doLogin.


#4

Yes, but you then have to get rid of the publicAPI variable (and the return), use var fred = new User() and use fred.doLogin(..)


#5

Exactly. I was replying to the orignal post - not yours. I wanted to point out the problem with having this.username and this.password in doLogin.

Edited to add: I realized I am making assumptions on what he’s trying to do.
He might be looking to do things exactly as you assumed.

My bad.