JoshieSimmons
JoshieSimmons

Reputation: 2791

How to reference function variables in JavaScript?

Experienced python user learning JavaScript.

Let's say that I define a function that takes two arguments:

function alpha(var_a, var_b){
 this.a = var_a;
 this.b = var_b;
}

And then write a sample object:

function One(){
 var a = [
   ["1"],
   ["2"],
   ["3"]
 ];

 var b = [
   ["4"],
   ["5"],
   ["6"]
 ];

 return new alpha(a, b);
}

If I had a third function that took as its argument a function:

function beta(alpha){
}

How could I reference, in this third function, the variables from the argument function?

Upvotes: 0

Views: 81

Answers (1)

Quentin
Quentin

Reputation: 944430

First you would have to call beta and pass it the instance of alpha the you get from calling One.

beta(One());

Then you can just access alpha.a and alpha.b inside it (noting that this alpha is the local variable alpha created by the function prototype's argument name and not the global alpha created by the function declaration).

NB: Convention dictates that you start a function name in JS with an uppercase character when, and only when, it is a constructor function. So you should have Alpha and one rather than alpha and One.


Let's rewrite all of that code with less confusing variable names.

function MyConstructor(var_a, var_b) {
    this.a = var_a;
    this.b = var_b;
}

function createInstanceWithData() {
    var a = [
        ["1"],
        ["2"],
        ["3"]
    ];

    var b = [
        ["4"],
        ["5"],
        ["6"]
    ];

    return new MyConstructor(a, b);
}

function logData(someInstance) {
    console.log(someInstance.a, someInstance.b);
}

logData(createInstanceWithData());

Upvotes: 6

Related Questions