Undefined property after passing an object as a parameter-Collection of common programming errors
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.
Originally posted 2013-11-10 00:11:43.