Skip to main content

Command Palette

Search for a command to run...

JavaScript Difference between assignment and definition

Updated
1 min readView as Markdown

In this article I lay out how assignment is different from definition.

    const getMe={
        __proto__: {
            get foobar() {
                return `${this.fb} is foobar!`
            },
            set foobar(v) {
                this.fb=v
            }
        }
    }

    // here, assiging foobar calls setter in prototype chain of getMe.
    getMe.foobar='steve'
    console.log(getMe.foobar)   // steve is foobar!

Output

steve is foobar!

Here, when getMe.foobar is assigned value steve, what is happening is that setter up its prototype chain is called.

In contrast to this, when we define a property using Object.defineProperties, we are defining a property that is getMe's own. We also call this property direct property.

   // now, for defining foobar instead.
    Object.defineProperties(getMe, {
        foobar: {
            value: 'bobby',     // now foobar prop is added as getMe's own property.
            writable: true
        }
    })

    console.log(getMe.foobar)   // bobby

Output

bobby

As you can see, we have added a new property with the same name foobar but this time as getMe's own. This is why getMe.foobar returns bobby as its own prop takes precedence over those up the prototype chain.

:)

More from this blog

Linux and Web

31 posts