I am writing a Javascript API library that provides consumers with an interface that allows them to interact with our backend servers. It is assumed that the consumer will write a javascript client web application that relies heavily on the API provided by the library.
I came up with this “template” to maintain state and make the functionality “accessible” as certain criteria are met (for example, an authenticated user is registered on the client side).
Is this an appropriate way to achieve this? Or am I involuntarily violating any convention or best practice that will later bite me?
// file: clientApi.js (library)
ClientObject = function () { this.objectname = "a client class"; } ClientObject.prototype.loginUser = function(name) { this.loggedin = true; if (typeof this.User === 'undefined') { this.User = new ClientObject.User(name); } } ClientObject.User = function (name) { this.username = name; } ClientObject.User.prototype.getProfile = function() { return 'user profile'; }
// file: app.js (consumer application)
var testClient = new ClientObject(); console.log('testClient.User = ' + (typeof testClient.User)); // should not exist testClient.loginUser('Bob'); // should login 'bob' console.log('testClient.User = ' + (typeof testClient.User)); // should exist console.log(testClient.User.username); // bob testClient.loginUser('Tom'); // should not do anything console.log(testClient.User.username); // bob still console.log(testClient.User.getProfile()); // tada, new functionality available
My question is: is this approach valid? Is there a pattern that I touch on that can offer a better explanation or a way to achieve my ultimate goal?
I asked a similar question here with a bunch of others, unfortunately, the above code was somewhat lost in noise: Javascript: creating an object from an already created object compared to the prototype
source share