Payaam
Payaam

Reputation: 135

Setting prototype in object literal

I am a beginner learning JavaScript. Reading through this page, I can't understand how this piece of code is defining an object. I expect the " foo: bar" construct and not sure if __proto__ is a builtin name or doing something special here. What is going on?

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences. MDN

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

Upvotes: 4

Views: 391

Answers (1)

Matt Mokary
Matt Mokary

Reputation: 727

That code snippet is really a bunch of syntactic sugar for plain old key: value notation.

__proto__: theProtoObj,

Yes, this is a special field, not just an arbitrary name. It is the object used when searching up the inheritance tree. Its' explicit use is generally discouraged. Read this Quora answer for a better understanding of it.

handler,

This is syntactic sugar for handler: handler. Frequently do you want to have a field in an object and assign it a value from a variable with the same name, so they included that shorthand in the specification.

var x = 10;
var y = 15;

// longhand
var point = { x: x, y: y };

// shorthand
var point = { x, y };

toString() {

This is syntactic sugar for:

var obj = {
    toString: function () {
        ...
    }
};

return "d " + super.toString();

The super keyword makes calling functions from a parent class much more clear. Where before it would look something like this:

var Person = function (name) {
    this.name = name;
}

var Engineer = function (name) {
    // "super call"
    Person.call(this, name);

    this.profession = 'Engineer';
}

Now it can look like this:

class Engineer extends Person {
    constructor (name) {
        super(name);

        this.profession = 'Engineer';
    }
}

[ 'prop_' + (() => 42)() ]: 42

Probably my favorite. This syntax allows you to have dynamic key names in the object literal. Before, you would have to do this:

var obj = {};
obj['prop_' + 42] = 42;

But, with the dynamic literal syntax, you can do this:

var obj = {
    ['prop_' + 42]: 42
};

(() => 42)()

Syntactic sugar for:

// create an anonymous function and call it immediately
(function () {
    return 42;
})();

Upvotes: 4

Related Questions