Saturday, 17 August 2013

Looking for some js scope hack

Looking for some js scope hack

Here some interesting behaviour of javascript function arguments variable
that you may be or maybe not aware of:
function foo(bar) {
console.log('bar was:', bar);
arguments[0] = 'zap';
console.log('bar now:', bar);
}
foo('bam');
// bar was: bam
// bar now: zap
As you can see bar variable now pointing out to another value.
I want to make use of such behavior in a slightly strange way, I want to
know is it possible to change argument value from the outside of the
function scope somehow?
Maybe using call/apply, or some other trycky js features?
So I can change the value of function argument after it was called, for
example:
function chooseNumber(number) {
setInterval(function() {
console.log('I choosed:', number)
}, 1000)
}
chooseNumber(1);
// I choosed: 1
// I choosed: 1
// I choosed: 1
// ...
Then if I dicided to change my mind, how can I make so that initial
function would output:
// I choosed: 2
// I choosed: 2
// I choosed: 2
// ...

No comments:

Post a Comment