Call a method of a Javascript class (OOP)

5

asked by anonymous 19.08.2014 / 19:03

3 answers

7

Reading the Rui Pimentel answer , it occurred to me that you could create an instance within the function itself, if it is called without new . The practical consequence of this is that you either call with or without new :

function SDK(dynamicUrl) {
    if(!(this instanceof SDK)) {
       return new SDK(dynamicUrl);
    }
    var data = 'DATA BITCH';
    var atual = null;
    var counter = 0;
    this.onComplete = function (){ }
    this.onError = function () { }
    this.start = function ( ) {
        alert('HUE BR')
    }
}
SDK().start();

link

I'm not sure if this solves the problem given its limitations, but the trick remains.

    
19.08.2014 / 20:34
4

No, you can not access an instance variable without having an instance for it. The start function is only created when creating an instance of class SDK . You can use some trickery to not call the new SDK() that behind the wipes would end up calling the "constructor", but that would only add unnecessary complication to your code.

    
19.08.2014 / 19:58
3

If you can add the line

return this;

As the last statement of the function / class SDK , then you can call the desired function by instantiating ( var a = new SDK(); a.start(); ) or not the prototype ( SDK().start(); ).

Edit: As pointed out by @bfavaretto, this method has the side effect of declaring, on the global object ( window ), the methods (and possibly the attributes) of the class that have been declared with this.metodo = function( ... ){ ... }; , so the function is executed ( SDK().start() ), because in this case, the this of the function will be window itself.

    
19.08.2014 / 20:05