David Ayres
David Ayres

Reputation: 105

JavaScript Constructor - How Does JavaScript Determine the Constructor?

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!

Upvotes: 0

Views: 32

Answers (1)

Quentin
Quentin

Reputation: 943561

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.

Upvotes: 1

Related Questions