I am trying to apply module pattern in JavaScript when I have my custom constructor. Let us take this example:
// Assume I need `name` as private
function Dog(name){
this.name = name;
}
I can rewrite above as:
function Dog(name) {
let dogName = name;
return {
getName : function () {
return dogName;
},
setName : function (name) {
dogName = name;
}
}
}
The above code does not have right constructor property and Dog.prototype and the prototype of object returned does not match.
To fix this I made 2 Fixes:
function Dog(name) {
let dogName = name;
return {
// Fix 1
constructor : Dog,
getName : function () {
return dogName;
},
setName : function (name) {
dogName = name;
}
}
}
let d2 = new Dog("Tony");
// Fix 2 : This is painful as every time I need to set this up
Object.setPrototypeOf(d2 , Dog.prototype);
As you can see Fix 2 is painful. Every time I have to create an object, I need to do this. Is there any better way?
Let us not deviate our discussion that getter and setter should be moved to prototype. Above is just a quick example I am using.
The problem here is you're returning an object literal in your "constructor", an object literal has the
Objectprototype. You should not be returning in the constructor, you should be assigning things tothislike you did in your first code snippet.This isn't a common pattern for implementing classes though, you're not even using the
prototypeso it's unclear why theprototypeis important to you. Obviously this approach allows you to close over a variable to make it "private" which wouldn't be possible using theprototype. However, this approach has more overhead because each instance ofDogwill have it's own function forgetNameandsetName, the standard convention for "private" variables and methods is to prefix them with an underscore so you can use theprototypeas intended.