Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created March 18, 2020 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/482854bf4d08e59fc0190f1d27eefa8e to your computer and use it in GitHub Desktop.
Save cferdinandi/482854bf4d08e59fc0190f1d27eefa8e to your computer and use it in GitHub Desktop.
classes vs. constructors in a revealing module pattern
<!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