Bob
Bob

Reputation: 175

Access Property from External Function

I am trying to setup a feature as follows.

function Class() {
}

Class.prototype.func = function(f) {
    var hello = "hello";
    setTimeout(f, 1000);
};

new Class().func(function() {
    alert(hello);
});

I want the f() function to be able to access the hello variable. The problem is that f() is not running in the context of the func() function.

I have tried using var hello = "hello"; and this.hello = "hello"; but neither work.

How can f() access hello?

Upvotes: 0

Views: 79

Answers (3)

Ben McCormick
Ben McCormick

Reputation: 25718

Pass it as a parameter

function Class(){
}
Class.prototype.func=function(f){
    var hello="hello";
    setTimeout(function(){
        f(hello)
    },1000);
};
new Class().func(function(hello){
    alert(hello);
});

Upvotes: 1

Pointy
Pointy

Reputation: 413712

Given the structure of the code you've got, there's no way for any "f" passed into "func" to access "hello".

You could however, do this:

Class.prototype.func=function(f){
    this.hello="hello";
    setTimeout(f.bind(this),1000);
};
new Class().func(function(){
    alert(this.hello);
});

JavaScript scoping is based on the lexical relationship between functions (declaring contexts). A variable declared with var is available to the function in which it's declared, and to all functions declared/instantiated within that function. In your case, the anonymous function is not declared inside "func", so no local variable of "func" can ever be visible to it. There's no way to dynamically expose the local scope from inside "func" either. (I generally forget about ignore eval() when answering questions like this, but here I don't think even eval() could work around the situation.)

Upvotes: 0

Quentin
Quentin

Reputation: 943209

It can't. The variable simply does not exist in the scope in which the function is defined.

You would need to expose it to a wider scope (e.g. by making it a property of the instance of the Class object or a global).

Upvotes: 0

Related Questions