quinton
quinton

Reputation: 439

Passing Scope from one function to another

I have an object litrel that has 2 anonymous functions defined as such:

obj = {
    funcA : function(){
        var a = 'a';
    },
    funcB : function(){
        // but how do you access the scope in 'funcA' to access variable 'a'?
        console.log(a)
    }
}

I do not want to pass any variables just the scope of 'funcA' - thoughts?

Upvotes: 0

Views: 905

Answers (3)

Matthew
Matthew

Reputation: 8426

Does this code do what you want? If not, I'm really curious as to why.

obj = {
    funcA : function(){
        this.a = 'a';
        alert(this.a);
    },
    funcB : function(){
        // but how do you access the scope in 'funcA' to access variable 'a'?
        alert(this.a);
    }
}

obj.funcA();
obj.funcB();

What is the difference between accessing the actual scope of a separate function and setting members on the parent object as I have done?

Also, since there isn't a way of passing scope, are you just going to use something similar to this code instead?

Upvotes: 0

RobG
RobG

Reputation: 147553

You can use the a closure with the module pattern to get access to variables in an outer scope. More than one function can accesses the variable:

var obj = (function() {

  var a;

  return {

    setA: function(value) {
      a = value;
      return a;
    },

    getA: function(value) {
      return a;
    },

    multiplyA: function(value) {
      a = a * value;
      return a;
    }
  };
}());


alert(    obj.setA(5)      );  // 5
alert(    obj.multiplyA(2) );  // 10
alert(    obj.getA()       );  // 10

See Douglas Crockford's article on Private Members in JavaScript. In this way, functions can share a common variable object on their scope chain. You still can't reference it or pass it to another function, but you might be able to get the functionality you want.

Upvotes: 1

alex
alex

Reputation: 490657

JavaScript scope doesn't work like that because it has (only) function scope (except when using the let keyword).

What you could do is...

obj = {
    a: 0,
    funcA: function() {
        this.a = 'a';
    },
    funcB: function() {
        console.log(this.a);
    }
};

jsFiddle.

Upvotes: 6

Related Questions