-1

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!

3
  • 2
    It's a constructor if you call it with new. Commented Nov 18, 2018 at 18:29
  • If you could easily access capitalizeString from outside the IIFE, you could do new capitalizeString("") and it would still "work" - then you would have used capitalizeString as 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 used class syntax with methods). Commented Nov 18, 2018 at 18:52
  • This question is similar to: What is this JavaScript pattern called where a function is defined by an IIFE returning a closure? Why is it used?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 23 at 20:18

1 Answer 1

1

So how does JavaScript know that PersonContructor is the constructor, and it's not capitalizeString?

Is it only because I'm returning it?

Because you are returning PersonContructor, PersonContructor is assigned to Person. You aren't returning capitalizeString, so it isn't assigned to Person.

If you were to later call new Person() it would know it is a constructor because you used the new keyword.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for your answer, I was a little puzzled over this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.