Akhror Khamidov
Akhror Khamidov

Reputation: 73

Factory Function JS

enter image description here

Hello, Can someone please explain me this const {r,g,b} = this; Why it has no variable name, if 'this' is the variable name, to what that 'this' pointing to?

function makeColor(r, g, b) {
    const color = {};
    color.r = r;
    color.g = g;
    color.b = b;
    color.rgb = function () {
        const { r, g, b } = this;
        return `rgb(${r},${g},${b})`
    }
}

Upvotes: 1

Views: 164

Answers (3)

NNL993
NNL993

Reputation: 472

Variable this doesn't even exist, this is one of the reserved words (such as break, for, function, let etc.), this in context you show directs to color constant, so in context you show this equals to color constant.

More about this at MDN.

Upvotes: 1

John Morton
John Morton

Reputation: 544

"this" is a special property of methods. When a function is called as a method of an object, as it is here, "this" refers to that object, in this case the color object, so the color.rgb() method will return the string "rgb(r,g,b)" where the r, g, and b there are the values fed to the makeColor function used to create that object.

Upvotes: 2

delibalta
delibalta

Reputation: 298

The word 'this' is not a variable. This is a relatively new concept. they call it object destructuring syntax.

Upvotes: 1

Related Questions