Jump to content

How to call method by pointer?


rain13
 Share

Recommended Posts

Hi!

Sorry if it is wrong word in the title. I am not sure how to call it in english if I do var x = functionName and then x() to call it. Just to clarify this is what I meant bycalling by pointer.  What I just described works normally. For example you can do x = alert and then use x() to actually call alert.

Now In my case I want to get the same thing work in class. How do I do that?

 

class MyClass {
	constructor(){
    	this.config = {"branch": this.branchA};
        this.classVar = {"a":1}
    }
    
    main(){
    	this.classVar["b"] = 2;
        this.branchB();
        this.config.branch();
    }
    
    branchA(){
        alert(this.classVar["a"]);
    }
    
    branchB(){
    	alert(this.classVar["b"]);
    }

}

var myClass = new MyClass();
myClass.main();
myClass.config.branch = myClass.branchB;
myClass.main(); // I want this.classVar to be accessible in both branchB calls


In this example first call from main to branchB works as I want but 2nd call complains that TypeError: this.classVar is undefined. How do I fix that?

Basically I want to have main method that has code that gets executed every time and then n possible alternations which are decided by configuration.

Link to comment
Share on other sites

I think it should work if you use strings instead. Selecting methods dynamically is going to be pretty confusing to anybody who has to maintain your code. I think it's a practice which should be avoided.

...
...

    constructor(){
    	this.config = { "branch": "branchA" };
        this.classVar = {"a":1}
    }
    main(){
    	this.classVar["b"] = 2;
        this.branchB();
        this[this.config.branch]();
    }


...
...

var myClass = new MyClass();
myClass.main();
myClass.config.branch = "branchB";
myClass.main();

 

  • Like 1
Link to comment
Share on other sites

Posted (edited)

Thanks.  It works.

How does 

this[this.config.branch]();    

exactly work? 

Basically calling string()? I mean normally,  "alert"() wouldnt work but this.config.branch is also string. why is there this and then square brackets?

Edited by rain13
Link to comment
Share on other sites

Javascript has a feature where you can access any object's properties or methods using square brackets and a string inside.

window.alert() is the same as window["alert"]().

myClass.value is the same as myClass["value"].

Since the square bracket notation uses a string instead of an identifier, you can put a variable containing a string within the square brackets.

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...