Created
March 18, 2020 03:21
-
-
Save cferdinandi/482854bf4d08e59fc0190f1d27eefa8e to your computer and use it in GitHub Desktop.
classes vs. constructors in a revealing module pattern
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Classes</title> | |
</head> | |
<body> | |
<script> | |
// This is a Contructor inside a Revealing Module Pattern | |
// It creates the scoped namespace for the entire set of methods | |
var Person = (function () { | |
// Create a contructor function | |
// Assingn the name property | |
var Constructor = function (name) { | |
this.name = name; | |
}; | |
// This is a private function | |
// It can only be used inside the Revealing Module Pattern | |
var log = function (msg) { | |
console.log(msg); | |
}; | |
// This method can be used externally because it's part of the Constructor prototype | |
// It uses an internal method | |
Constructor.prototype.sayHi = function () { | |
log('Hello ' + this.name); | |
}; | |
// Return the Constructor so that it can be used externally | |
return Constructor; | |
})(); | |
var steve = new Person('Steve'); | |
steve.sayHi(); | |
// This is a class | |
// It creates the scoped namespace for the entire set of methods, just like the Revealing Module Pattern does | |
// With a class, you don't need to return anything | |
class Dog { | |
// You still need to create a constructor | |
constructor (name) { | |
this.name = name; | |
} | |
// There is no such thing as a private method in a class | |
// You can fudge it, though | |
_log (msg) { | |
console.log(msg); | |
} | |
// This method can be used externally | |
// It uses an internal method | |
sayWoof () { | |
this._log('Woof ' + this.name); | |
} | |
} | |
var kevin = new Dog('Kevin'); | |
kevin.sayWoof(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment