Created
November 7, 2018 10:23
-
-
Save josemariagarcia95/4089b0e4ec4181c972545f9f1319f6bd to your computer and use it in GitHub Desktop.
Template Method Pattern in Javascript using prototypes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parent Class A | |
*/ | |
function A() { | |
this.name = 'Clase A'; | |
} | |
A.prototype.function2 = function() { | |
console.log( 'Function 2 in A' ); | |
}; | |
A.prototype.function3 = function() { | |
console.log( 'Function 3 in A' ); | |
}; | |
/** | |
* Template function. We will override function2 and function3 in child classes | |
*/ | |
A.prototype.function1 = function() { | |
this.function2(); | |
this.function3(); | |
}; | |
/** | |
* Child class B | |
*/ | |
function B() { | |
// We could omit this line since there are no properties to share. | |
A.call( this ); | |
} | |
// We copy the A prototype into B, so it has function1, function2 and function3. | |
B.prototype = Object.create( A.prototype ); | |
// We override function2 and function3 | |
B.prototype.function2 = function() { | |
console.log( 'Function 2 in B' ); | |
}; | |
B.prototype.function3 = function() { | |
console.log( 'Function 3 in B' ); | |
}; | |
/** | |
* Child class C | |
*/ | |
function C() { | |
// We could omit this line since there are no properties to share. | |
A.call( this ); | |
} | |
// We copy the A prototype into C, so it has function1, function2 and function3. | |
C.prototype = Object.create( A.prototype ); | |
// We override function2 and function3 | |
C.prototype.function2 = function() { | |
console.log( 'Function 2 in C' ); | |
}; | |
C.prototype.function3 = function() { | |
console.log( 'Function 3 in C' ); | |
}; | |
const b = new B(); | |
const c = new C(); | |
b.function1(); | |
// Function 2 in B | |
// Function 3 in B | |
c.function1(); | |
// Function 2 in C | |
// Function 3 in C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment