Search code examples
javascriptfunctionmember

Declaring a member function in JS


I've tried two ways to declare a member function in JS:

function init() {
    var name = "Mozilla";
    function displayName() {
        alert(name);
    }
}
a = new init();
a.displayName()

And

function init() {
    var name = "Mozilla";
    displayName = function() {
        alert(name);
    }
}
a = new init();
a.displayName()

The first method told me that displayName() is undefined. The way I see it a variable of type Function with name displayName is created, and thus it should work. Any one care to explain why it didn't work?


Solution

  • To create something like a member function you need to add it to the protoype of the constructor function:

    function init() {
        this.name = 'Mozilla';
    }
    init.prototype.displayName = function() {
        alert(this.name);
    }
    

    I also highly recommend you to read something about how the object system in JavaScript works. There's a pretty good article about it on MDN: https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript