0

We can't change the below code:

var t = 10;

function test(){
  var t = 20;
  alert(this.t);
}

We have to change or add below this.

test();

the above function call execute 10;

I need "20" which is defined inside the function test.

5 Answers5

3

Since you cannot change the function, you can do this

test = test.bind({t: 20});
test();

Or in a single line

test.bind({t: 20})();
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • You didn't read the first line of the question, did you ? – Denys Séguret Feb 25 '14 at 08:05
  • @dystroy you are correct. We cant change inside function. Is there any object initiation or some thing else for test function? –  Feb 25 '14 at 08:08
  • @dystroy Well, I had to think for a while after seeing your first comment. But I believe our answers have different impacts. My first version binds the object. So, next time onwards he doesn't have to pass the object :) – thefourtheye Feb 25 '14 at 08:18
3

You can do this :

test.call({t:20});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Looks like you need to read up on how JS resolves names (through scope scanning, namely), and how the this keyword is bound. I've dealt with this in detail here, and linked to other resources which goes into more detail of several aspects.

The long and short of it is that your function should look like this:

function f ()
{
    var t = 20;
    alert(t);//console.log would be better, though
}

With the code, as it stands, you can't get to the var value. You'll have to change some of the code, or change how you invoke the function:

var obj = {t: 20, test: test};//test is the function name:
obj.test();//this.t will reference obj.t now

Read the linked answers why and how this works

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
0

if you call test() it will be as a function and this will be global object (window). if you add new keyword (new test();) then it will be an object and this will refer to that object. But you will need to also store t in this:

function test(){
  this.t = 20;
  alert(this.t);
}

new test();

or you can store that in var and access it using that var:

function test(){
  var t = 20;
  alert(t);
}

test();
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • My original answer had something similar, but the question's first line reads `We can't change the below code:` :) – thefourtheye Feb 25 '14 at 08:16
  • @user3350129 it's valid question. The answer is that you can't get `var t = 20;` using `this.t;` it's different variable. it's like access `var x` with `y`. – jcubic Feb 25 '14 at 08:22
  • Thanks jcubic and all other answers and discussions. Really brief enough. –  Feb 25 '14 at 08:47
0

You could do this :

alert(20);

Seriously, you've probably misunderstood your teacher's instructions.