Skip to content

Commit 0596b5c

Browse files
committed
partial fix: what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor
1 parent 14f54cf commit 0596b5c

File tree

1 file changed

+7
-5
lines changed
  • questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor

1 file changed

+7
-5
lines changed

questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ The main advantage of using an arrow function as a method inside a constructor i
88

99
For example, let's say we have a `Person` constructor that takes a first name as an argument has two methods to `console.log()` that name, one as a regular function and one as an arrow function:
1010

11-
```js
11+
```js live
1212
const Person = function (name) {
1313
this.name = name;
1414
this.sayName1 = function () {
@@ -68,12 +68,14 @@ const myFunction = (arg1, arg2, ...argN) => expression;
6868

6969
### Examples
7070

71-
```js
71+
```js live
7272
// Arrow function with parameters
7373
const multiply = (x, y) => x * y;
74+
console.log(multiply(2, 3)); // Output: 6
7475

7576
// Arrow function with no parameters
7677
const sayHello = () => 'Hello, World!';
78+
console.log(sayHello()); // Output: 'Hello, World!'
7779
```
7880

7981
### Advantages
@@ -86,7 +88,7 @@ const sayHello = () => 'Hello, World!';
8688

8789
Arrow functions cannot be used as constructors and will throw an error when used with the `new` keyword.
8890

89-
```js
91+
```js live
9092
const Foo = () => {};
9193
const foo = new Foo(); // TypeError: Foo is not a constructor
9294
```
@@ -104,7 +106,7 @@ arrowFunction(1, 2, 3);
104106

105107
Since arrow functions do not have their own `this`, they are not suitable for defining methods in an object. Traditional function expressions or function declarations should be used instead.
106108

107-
```js
109+
```js live
108110
const obj = {
109111
value: 42,
110112
getValue: () => this.value, // `this` does not refer to `obj`
@@ -119,7 +121,7 @@ One of the most notable features of arrow functions is their behavior with `this
119121

120122
### Arrow functions inside function constructors
121123

122-
```js
124+
```js live
123125
const Person = function (name) {
124126
this.name = name;
125127
this.sayName1 = function () {

0 commit comments

Comments
 (0)