Sophivorus Sophivorus - 16 days ago 4
Javascript Question

Undefined property after passing an object as a parameter

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"?

Answer

bar 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();‚Äč