javascript - Undefined property after passing an object as a parameter - Stack Overflow

function foo() {bar = 'ok';new baz( this );}function baz( foo ) {alert( foo.bar );}new foo(

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 badges
Add a ment  | 

4 Answers 4

Reset to default 4

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();​

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...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742394711a4435711.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信