I have a JavaScript function like this:
obj.use('hello', function () {
// Here I want to access the string 'hello'
});
Is this at all possible, or are there any good workarounds that I can use?
I have a JavaScript function like this:
obj.use('hello', function () {
// Here I want to access the string 'hello'
});
Is this at all possible, or are there any good workarounds that I can use?
My answer is based on the assumption that your usage indicates use
as being a method of the object obj
. In which case the way to achieve your objective is to use the same object to store the first parameter to obj.use
.
var obj = {
use: function(greeting, fn) {
obj.greeting = greeting;
fn();
}
}
obj.use('hello', function () {
console.log(obj.greeting); //output: 'hello'
});
// Here I want to access the string 'hello'
Well that's easy, you just store the string in a variable whose scope is accessible inside the method:
var greeting = 'hello';
obj.use(greeting, function () {
console.log(greeting); // logs "hello"
});