Sonny
Sonny

Reputation: 8326

Accessing "Parent Scope"

Disclaimer: I'm not sure that I'm using the correct terminology.

Given this code:

var sample = 'Text';
var test = function(sample) {
    console.log(sample);
};
test('Text Too');

I am aware that if the function parameter had a different name, the console.log() call would output "Text". Is there a way for the test() function to reference the "parent scope" variable, sample without changing the name of the function parameter? If so, how?

Upvotes: 0

Views: 255

Answers (2)

caffeinated.tech
caffeinated.tech

Reputation: 6548

@plbsam is right, he shouldn't have deleted his answer.

In your specific case, this inside a function is the context it is called in: docs

var sample = 'Global var';
var test = function(sample) {
  console.log("sample: "+sample);
  console.log("this.sample: "+this.sample);
};
test('Local var');

EDIT:

as this all depends on the scope the function is called in you can always assign this to a separate var in the global scope to be able to access it anywhere:

// this var can now be accessed inside any function as a reference to the global scope.
global = this;

var sample = 'Global';
var test = function(abc) {
  console.log("sample: "+sample);
  console.log("this.sample: "+this.sample);
  console.log("global.sample: "+global.sample);
};
test('Local');

Upvotes: 2

hon2a
hon2a

Reputation: 7214

No, there is no way to do this in JavaScript. If you use the same variable name in the inner scope, the outer scope variable becomes completely inaccessible to that inner scope.

Edit: Except, of course, when the outer scope is the global scope. Then you could use window.sample.

Upvotes: 2

Related Questions