function foo() {
bar = 'ok';
new baz( this );
}
function baz( foo ) {
alert( foo.bar );
}
new foo();
Why is it that the alert shows "undefined" instead of "ok"?
function foo() {
bar = 'ok';
new baz( this );
}
function baz( foo ) {
alert( foo.bar );
}
new foo();
Why is it that the alert shows "undefined" instead of "ok"?
Share Improve this question edited Nov 23, 2016 at 12:55 Sophivorus asked Aug 10, 2012 at 0:07 SophivorusSophivorus 3,0833 gold badges35 silver badges43 bronze badges4 Answers
Reset to default 4bar
has gone out of scope. There is a difference between scope and context. if you want to attach a property to foo
, you must attach the property to the function.
function foo() {
this.bar = 'ok';
new baz(this);
}
function baz(foo) {
alert(foo.bar);
}
new foo();
Its because foo.bar is a private variable. Change it to this and it'll work
function foo() {
this.bar = 'ok';
new baz(this);
}
function baz(foo) {
alert(foo.bar);
}
new foo();
Because variables are not properties (except WRT global variables/properties). You're creating a global variable bar
by not using the var
statement. Even if you use var
, it doesn't show up on the object being constructed.
Since you're using new
, you can set the property on this
.
this.bar = "ok"
So full code is...
function foo() {
this.bar = 'ok';
new baz(this);
}
function baz(foo) {
alert(foo.bar);
}
new foo();
By the way, the new
keyword is wasted on baz
since you're not retaining any object created.
In your baz
function foo
is not being passed as a reference, it's a placeholder for a parameter. When you do new foo
you're using foo
as a constructor. bar
is global since it hasn't been declared with var
or this.bar
. I think you need to revisit the basics, this question is too wrong...