0

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?

1
  • The object returned by Thing does not have any methods. All you do inside the constructor function is creating a local function. That function is garbage-collected after Things terminates. It works the same way like with any other function. Commented Dec 13, 2012 at 15:29

1 Answer 1

3
//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();
Sign up to request clarification or add additional context in comments.

1 Comment

The OP can do so in his own time if he feels this is the best answer, he doesn't need to accept it just because you were the first to solve his problem. Anyway, you could add some more explanation as to why it is needed ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.