Skip to content

Commit f0e7f61

Browse files
committed
objects-classes, ch4: clarifying nuance of concise methods not being valid with 'new' operator, closes #1801
1 parent 9be25c4 commit f0e7f61

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

objects-classes/ch4.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,14 +290,24 @@ We've so far seen three different ways of context assignment at the function cal
290290
A fourth way to call a function, and assign the `this` for that invocation, is with the `new` keyword:
291291

292292
```js
293-
var point = { /* .. */ };
293+
var point = {
294+
// ..
295+
296+
init: function() { /* .. */ }
297+
298+
// ..
299+
};
294300

295301
var anotherPoint = new point.init(3,4);
296302

297303
anotherPoint.x; // 3
298304
anotherPoint.y; // 4
299305
```
300306

307+
| TIP: |
308+
| :--- |
309+
| This example has a bit of nuance to be explained. The `init: function() { .. }` form shown here -- specifically, a function expression assigned to a property -- is required for the function to be validly called with the `new` keyword. From previous snippets, the concise method form of `init() { .. }` defines a function that *cannot* be called with `new`. |
310+
301311
You've typically seen `new` used with `class` for creating instances. But as an underlying mechanism of the JS language, `new` is not inherently a `class` operation.
302312

303313
In a sense, the `new` keyword hijacks a function and forces its behavior into a different mode than a normal invocation. Here are the 4 special steps that JS performs when a function is invoked with `new`:

0 commit comments

Comments
 (0)