Object with constructors in javascript

Ok, I have a question and I don't know the answer. I am creating an object and the properties of an object are constructor functions. Now in these constructor functions I am referencing this. Will this variable be related to the parent object, so if I create this.submit in each of the constructors, it will overwrite the previous definition?

The reason I am doing this is because I iterate over every property in my object and if it is a function, I extend my prototype with a Node Event Emitter so I can dispatch events after successful ajax calls.

Here's an example:

var AccountMethods = function(apiVersion){

    return {
        /** Used to login users
         *
         * @param username - {string} Username
         * @param password - {string} Password
         * @function
         *
         * @example
         * var Login = new Easy.Login('fakeusername', 'fakepassword')
         * Login
         *     .on('done', function(data){
         *         if(data.success){
         *              // user is logged in
         *         } else{
         *             throw new Error(data.error);
         *         }
         *     })
         *     .on('error', function(err){
         *         // do something with err
         *     });
         */
        Login: function (username, password) {
            this.submit = function () {
                $.post(apiVersion + 'account/login', {
                    username: username,
                    password: password
                })
                    .done(function (data) {
                        if(data.success){
                            this.emit('done', data);
                        } else{
                            this.emit('error', data)
                        }
                    }.bind(this))
                    .fail(function (err) {
                        this.emit('error', {
                            error: err.status + ' ' + err.statusText + ' : ' + err.responseText
                        });
                    }.bind(this));
            }
        },
        /** Used to logout users
         *
         * @function
         *
         * @example
         * var Logout = new Easy.Logout();
         *
         * Logout.on('done', function(){
         *     // user is logged out
         * });
         *
         * Logout.submit();
         */
        Logout: function () {
            this.submit = function () {
                $.post(apiVersion + 'account/logout')
                    .done(function (data) {
                        this.emit('done');
                    }.bind(this))
                    .fail(function (err) {
                        this.emit('error', err);
                    }.bind(this));
            }
        },
    }
}

      

You can see in the example using comments. This definitely works the way I want, but right?

I can do this and it works as expected:

var Login = new Easy.Login('fakeusername', 'fakepassword');
Login.submit();

var Logout = new Easy.Logout();
Logout.submit();

      

Both submit functions are set inside the same parent using this.submit = ... but it works as expected. Can someone explain this to me?

+3


source to share


1 answer


When you call the constructor with new

, the new empty object will bind to it as this

, so inside the function this

will refer to the new object that is being created (i.e. what will be returned from the call new Link()

.) This means that in your example, variables Login

and Logout

are different objects with different sending methods.

If someone tried to call Login

without new

, then the value this

will depend on the calling context: if called as Easy.Login

, then it this

will refer to Easy

, but if the call as directly reference the function, then the value this

will depend on whether strict mode is enabled or not. (See Matt Brown's comment below)



Overall: as long as you only use them as constructor functions, this approach is correct. But as you can see, not calling constructor functions as they were meant to be called can be problematic, so the convention is that constructor function names start with capital letters (which you follow correctly) so people don't make the mistake of calling them without new

(most static code analyzers will warn you by default not to follow this convention).

+2


source







All Articles