Search code examples
javascriptobjectobject-literal

Getting data from object literal


I have an object literal where I can set a persons name. In another .js-file I have an object where I instantiates the Person-object, and with the function "getName" i want to assign a persons name to a variable.

However, when I try to do that I don't get the persons name. Instead I get the whole function. Why is it this way?

function Person(name){

    this.getName = function(){
        return name;
    }
}

init: function(){
    var person = new Person("thomas");
    var name = person.getName;
    alert(name) // <- the function instead of the name


Solution

  • Change your code from:

    var name = person.getName;
    

    To:

    var name = person.getName();