Skip to content

Commit 66ac856

Browse files
committed
New post on pseudoclassical and prototypical patterns
1 parent a4446a4 commit 66ac856

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

.DS_Store

2 KB
Binary file not shown.
File renamed without changes.

_posts/2015-06-14-pseudoclassical.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
---
2+
title: Prototypical vs Pseudoclassical Pattern
3+
---
4+
5+
Classes are a core feature of Javascript which make it easier to write complex and powerful functionality. However, Javascript has four different patterns for creating and instantiating classes, and it can sometimes be easy to confuse them.
6+
7+
The four patterns are:
8+
1. Functional
9+
2. Functional-shared
10+
3. Prototypical
11+
4. Pseudoclassical
12+
13+
In this post, I will compare two of the most popular patterns: Prototypical and Pseudoclassical.
14+
15+
### Prototypical
16+
17+
var Animal = function(name) {
18+
var animal = Object.create(Animal.prototype);
19+
animal.name = name;
20+
return animal;
21+
}
22+
Animal.prototype.shout = function(message) {
23+
alert(message);
24+
};
25+
26+
var lion = Animal('Scar');
27+
console.log(lion.name); // logs 'Scar'
28+
lion.shout('Roar!!!!'); // alerts 'Roar!!!!'
29+
30+
### Pseudoclassical
31+
32+
var Animal = function(name) {
33+
this.name = name;
34+
}
35+
Animal.prototype.shout = function(message) {
36+
alert(message);
37+
};
38+
39+
var lion = new Animal('Scar');
40+
console.log(lion.name); // logs 'Scar'
41+
lion.shout('Roar!!!!'); // alerts 'Roar!!!!'
42+
43+
As you can see, these patterns are very similar. When defining the class, you may have noticed that the prototypical pattern has a few extra steps. Namely, you must call the Object.create function with the class's prototype object to pass in all the associated methods. Then we must assign any properties that are passed in at instantiation. Finally, we must return our new object.
44+
45+
The pseudoclassical pattern bypasses most of these steps. By including the 'new' keyword when we instantiate a new class, the interpreter will automatically inject the code that creates a new object and then will return it. Furthermore, it will bind the keyword 'this' to the new instance of the class, allowing us to assign properties in the class constructor function body using 'this'.
46+
47+
For these reasons, many engineers (including myself) prefer the pseudoclassical pattern.

0 commit comments

Comments
 (0)