Alfie Woodland
Alfie Woodland

Reputation: 834

Calling a method in Javascript

I'm totally new to Javascript and this seems like something that should be very simple, but I can't see why my code isn't working. Here's an example of the problem I'm having:

//Thing constructor
function Thing() {
    function thingAlert() {
        alert("THING ALERT!");
    }
}

//Make a Thing
var myThing = new Thing();

//Call thingAlert method
myThing.thingAlert();

An object is created, but I can't call any of its methods. Why, in this example, is thingAlert() not being called?

Upvotes: 0

Views: 76

Answers (1)

flavian
flavian

Reputation: 28511

//Thing constructor
function Thing() {
    this.thingAlert = function() {
        alert("THING ALERT!");
    };
};
// you need to explicitly assign the thingAlert property to the class.
//Make a Thing
var myThing = new Thing();

//Call thingAlert method
myThing.thingAlert();

Upvotes: 3

Related Questions