0

I have a javascript like the following on my main page: It just defines a variable

test1 = function(){
var bla= "bla";
}

In my iFrame, I have another javascript which only produces an alert like the following

alert(parent.test1.bl);

Unfortunately, the alert window appears but the content says "undefined". How can I read a variable from within a function in the parent window?

The funny part is that if I execute the alert at the parent window and call only the function from within the iFrame, the alert box pops up and the message is included. But it seems that it is not possible to read a variable from the parent.

2
  • I think you mean parent.window.variable? Commented Dec 21, 2012 at 17:45
  • 1
    The last part of your question is not clear. Here is what the alerts do: jsfiddle.net/rpsu8 Commented Dec 21, 2012 at 17:53

1 Answer 1

3

Functions haven't properties, objects have. So you've to instantiate test1() before trying to use its properties.

test1 = function(){
    var bla= "bla";
    this.bl ="notbla";
}

alert(new test1().bl);

Notice the usage of the keyword this here, which refers to the newly created object, and makes bl a property, that can be read outside of the function. bla declared with var can't be seen outside of test1(), unless you won't create another property like this.bl = bla;

The "funny part" of your question really is unclear, definitely your alert() will show undefined, no matter where it's invoked.

Functions and Objects at MDN.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Teemu, Works like a charm!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.