I'm currently learning everything I can about OOP with JavaScript, and I've got the following code:
var Person = (function() {
var protectedMembers;
function capitalizeString(str) {
return str.charAt(0).toUpperCase() + string.slice(1);
}
function PersonConstructor(name, surname, protected) {
protectedMembers = protected || {};
protectedMembers.capitalizeString = capitalizeString;
this.name = capitalizeString(name);
this.surname = capitalizeString(surname);
}
return PersonConstructor;
}());
So how does JavaScript know that PersonContructor is the constructor, and it's not capitalizeString? I mean, I know that I mean for the function PersonConstructor to be the constructor, but how does the JavaScript engine or whatever determine that? Is it only because I'm returning it? Or is it because I'm using "this" in PersonConstructor? Or is it due to both things?
I did look at other StackOverflow questions which talk about JavaScript and constructors, but they didn't answer this specific question unless I missed something.
Thanks!
new.capitalizeStringfrom outside the IIFE, you could donew capitalizeString("")and it would still "work" - then you would have usedcapitalizeStringas a constructor. Of course you wouldn't do that because it doesn't make sense (the function is not initialising any properties), but JS doesn't stop you from doing it (it would if you had usedclasssyntax with methods).