JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at some basic coding and design patterns.
Privileged Methods
Privilege methods is a term coined by Douglas Crockford.
These are public methods that can access private methods and properties.
They act as a bridge to make some private functionality available in a controlled manner.
For instance, we can write:
let APP = {};
APP.dom = (() => {
const setStyle = function(el, prop, value) {
console.log('setStyle');
};
const getStyle = function(el, prop) {
console.log('getStyle');
};
return {
setStyle,
getStyle,
//...
};
}());
We have the setStyle and getStyle functions that are defined in the IIFE.
We expose them by return the object and then assigning it to a property that’s available outside the function.
These functions can have private variables inside them so that we can do whatever we want without exposing everything.
Immediate Functions
Immediate functions let us keep global namespace clean by wrapping our code in an anonymous function and run them immediately.
For instance, we can write:
(function() {
// ...
}());
to create a function and call it immediately.
This way, we can keep private variables and methods inside it.
For example, we can write:
let APP = {};
APP.methods = (() => {
function _private() {
// ...
}
return {
foo() {
console.log('...');
_private();
},
bar() {
console.log('...');
}
};
}());
We have the IIFE, which returns an object with the foo method that calls the private _private function.
Modules
ES5 doesn’t have modules, so we may have to use modules for scripts if we’re writing scripts for the browser.
For instance, we can create a module by writing:
let APP = {
module: {}
};
APP.module.foo = (() => {
const another = APP.module.another;
let foo, bar;
function hidden() {}
//...
return {
hi() {
return "hello";
}
};
}());
We created a foo module which references an another module.
In the module, we defined some variables and the hidden function.
And we return a public hi method in an object.
Then we can hi by writing:
APP.module.foo.hi()
Chaining
Chaining is a pattern that lets us call multiple methods in one line.
The methods are linked to a chain.
For instance, we can write:
class Foo {
foo() {
this.foo = 'foo';
return this;
}
bar() {
this.bar = 'bar';
return this;
}
baz() {
this.baz = 'baz';
return this;
}
}
We have multiple methods that return this , which is the Foo instance.
This way, we can call the methods in a chain.
So we can write:
new Foo().foo().bar().baz();
to call the chain of methods.
Conclusion
We can have private variables, objects, and functions that are inside a function.
Also, we can create our own modules with our own objects.
And we can make them chainable by returning this in a method.