0

I have this method:

var stopwatch = function () {
    this.start = function () {
        (...)
    };

    this.stop = function() {
        (...)
    };
};

When I try to invoke it:

stopwatch.start();

I am getting Uncaught TypeError: Object (here is my function) has no method 'start'. What am I doing wrong?

4 Answers 4

2

You are assigning functions to this.start and this.stop when the function stopwatch is run and never running that function.

It looks like you want a constructor function, with some prototypes.

// By convention, constructor functions have names beginning with a capital letter
function Stopwatch () {
    /* initialisation time logic */
}

Stopwatch.prototype.stop = function () { };
Stopwatch.prototype.start = function () { };

// Create an instance
var my_stopwatch = new Stopwatch();
my_stopwatch.start();
Sign up to request clarification or add additional context in comments.

Comments

1

Why not just do new stopwatch().start()?

2 Comments

Because you can't end that stopwatch later without saving it in a variable.
So, why not assigning the instance to a variable, like other answers do? :P
1

You need to call the start function as like this,

var obj = new stopwatch();
obj.start();

You can create an instance of that method and access the start function.

Comments

1

You need to create a new object first, only then you can call functions on it:

var stopwatch = function () {
    this.start = function () {
        console.log('test');
    };

    this.stop = function () {

    };
};

var s = new stopwatch();
s.start();

http://jsfiddle.net/9EWGK/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.