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.
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.
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})();
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
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();
You could do this :
alert(20);
Seriously, you've probably misunderstood your teacher's instructions.