简体   繁体   中英

Why can't I set this variable in an object with an object with javascript?

Why cant I do this I do not understand?

function hello() {
    this.say = 'fdfsd';
}
function goodbye() {
    this.example = new hello();
}

But it works if I do;

function hello() {
    this.say = 'fdfsd';
}
function goodbye() {
    this.example = false;
}
var goodbye = new goodbye();
goodbye.example = new hello();

You have to construct goodbye

var x = new goodbye();

Invoking the constructor will create a new object (of type goodbye ).

This line will construct an object of type hello and assign it to the example attribute of the goodbye instance

this.example = new hello();

After construction this is what the instance of goodbye will contain

// x
{
    example: {
        say: "fdfsd"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM