最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论
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...

发布评论

评论列表(0)

  1. 暂无评论