Self-references in object literals/initializers
P粉921130067
P粉921130067 2023-08-29 12:38:19
0
2
411

Is there any way to make something like the following work in JavaScript?

var foo = { a: 5, b: 6, c: this.a this.b // Doesn't work };

In its current form, this code obviously throws a reference error because this does not reference foo. ButyesIs there any way to make the value in an object literal property dependent on other previously declared properties?

P粉921130067
P粉921130067

reply all (2)
P粉615829742

You can do this:

var foo = { a: 5, b: 6, init: function() { this.c = this.a + this.b; return this; } }.init();

This will be some kind of one-time initialization of the object.

Note that you are actually assigning the return value ofinit()tofoo, so you mustreturn that value.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!