Skip to content

Commit

Permalink
Merge pull request #4 from hax/this-param
Browse files Browse the repository at this point in the history
Allow explicit this parameter without renaming
  • Loading branch information
gilbert authored Jan 10, 2020
2 parents 596b49e + c39a6b4 commit bbb5808
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,32 @@
> `this` isn't really a keyword, it is the natural "main" function argument in JavaScript.
> - (@spion)[https://github.com/mindeavor/es-pipeline-operator/issues/2#issuecomment-162348536]
This proposal extends the `function` declaration syntax to allow for explicit naming of what is normally called `this`. Its primary use case is to play nicely with the [function bind proposal](https://github.com/zenparsing/es-function-bind), making such functions more readable. For example:
This proposal extends the `function` declaration syntax to allow for explicit naming of what is normally called `this`.

```js
Object.defineProperty(User.prototype, {
get: function fullName() { // original version
return `${this.firstName} ${this.lastName}`
},
configurable: true,
})

// versions use the feature of this proposal

function fullName(this) { // explicit this parameter
return `${this.firstName} ${this.lastName}`
}

function fullName(this user) { // explicit naming `this` to `user`
return `${user.firstName} ${user.lastName}`
}

function fullName(this {firstName, lastName}) { // destructuring
return `${firstName} ${lastName}`
}
```

Its primary use case is to play nicely with the [function bind proposal](https://github.com/zenparsing/es-function-bind), making such functions more readable. For example:

```js
function zip (this array, otherArray) {
Expand Down Expand Up @@ -64,6 +89,22 @@ function process (this obj, name) {
};
```

Explicit `this` parameter also allow type annotation or parameter decorators be added just like normal parameter.

```ts
// Type annotation (TypeScript, already possible today)
Number.prototype.toHexString = function (this: number) {
return this.toString(16)
}
```

```ts
// Parameter decorators (future proposal)
Number.prototype.toHexString = function (@toNumber this num) {
return num.toString(16) // same as Number(num).toString(16)
}
```

## Behavior

If a function explicitly names `this`, attempting to use `this` inside the body will throw an error:
Expand Down

0 comments on commit bbb5808

Please sign in to comment.