简体   繁体   中英

How use properly THIS in javascript OOP

I'm using the Object.init pattern in my application. Where within the init i initialize variables attached to the object, for example:

var MyObject = {

 init: function() {
   this.element = $('.someElement');


   this.element.bind('click', this._doSomething.bind(this));
 },

 _doSomething = function() {
    // METHOD WHICH I WILL MANIPULATE THIS.ELEMENT

 }

};

What i'm trying to know is, if i have to create some variables inside the method _doSomething, should i attach the variables to the MyObject with this, like this:

this.someVar = 'something';

Or should i use var:

var someVar = 'something';

I think the best way is use this if i will use the someVar in other parts of MyObject, and i should var if i use only in the scope of _doSomething method.

But this is my opinion, i want know the best practice.

Thanks.

Your presumption is correct; use this.myVar for anything with a lifetime longer than one function.

To give you a better idea of how this works, your object can associate a string key like "myVar" with a variable. this.myVar is shorthand for this["myVar"] . Might look a little weird, but that's standard for setting/retrieving JS properties.

However, var myVar declarations are not associated with any one object; they survive for the lifetime of the function. They can be preserved if you have a function inside of a function, but that's not what you were asking about. If you are curious though, look up the term "closures".

The fact you named your function _doSomething, tells me it's a candidate for an IIFE . It's not accessible to the outside and you can interface with your object using foo.init();

Edit: changed listener, as per comment

jsfiddle

var foo = (function(){

    // private function
    function doSomething() {
    // METHOD WHICH I WILL MANIPULATE THIS.ELEMENT
        alert('doSomething()');
    }

    var myObject = {
        init: function() {
            this.message = 'hello init';
            this.element = $('.someElement');
            this.element.on('click', function() { doSomething.call(this); }.bind(this));
            alert(this.message);
        }
    };

    return myObject;

})();

foo.init();

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