Aaron
Aaron

Reputation: 11673

Why won't this function work in an Object-Oriented style of javascript?

I am trying to access the function as a method of the person object why won't it access the method and do what the function is supposed to do?

function Person(name, age, location) {
this.name= name;
this.age = age;
this.location = location;
this.test = function() {
    alert("TEST");
};

}   
var Matt = new Person("Matthew", "21", "South Africa");
Matt.test;

Upvotes: 1

Views: 66

Answers (2)

Alex Emilov
Alex Emilov

Reputation: 1271

Well since its a function use:

Matt.test();

Upvotes: 2

McStretch
McStretch

Reputation: 20645

You need to call the method with parenthesis:

Matt.test();

This will execute the function. Otherwise what you're getting with Matt.test is the function itself, which can be passed into another function, stored inside a variable, etc. Then you could execute this function at a later time.

Upvotes: 8

Related Questions