0

I'm trying to create a simple marquee that simply changes in intervals. I am just trying to understand objects in Javascript. Currently, I am receiving the error, object is not a function.

var marquee = {

            domElement: jQuery( 'span' ),
            titles: [ 'First', 'Second', 'Third', 'Fourth' ],
            current: '',
            next: 0,

            _getCurrent: function(){

                this.current = this.domElement.text();

            },

            _setNext: function(){

                this.next = this.titles.indexOf( this.current ) + 1;

            },

            changeHeading: function(){

                this._getCurrent();
                this._setNext();
                this.domElement.text( this.titles[ this.next ] );

            }

        };

var marqueeInterval = setInterval( marquee.changeHeading, 700 );

Any help on why I can't get this to work would be greatly appreciated. I am new to Object Oriented Javascript, and am just trying to understand. Thanks!

3 Answers 3

3

By passing the function reference of changeHeading to setInterval, you will lose context on each call. You either prevent that by adding an additional function like

setInterval(function() {
    marquee.changeHeading();
}, 700);

or invoke Function.prototype.bind like

var marqueeInterval = setInterval( marquee.changeHeading.bind( marquee ), 700 );
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! So basically, "this" no longer refers to marquee when being passed to setInterval? Am I understanding this correctly?
2

Since you are passing marquee.changeHeading as a callback to the setInterval() method, when the method is invoked the execution context will not be marquee object

You can either use the Function.bind() as shown below

var marqueeInterval = setInterval( marquee.changeHeading.bind(marquee), 700 );

or a custom callback which will invoke the target method like

var marqueeInterval = setInterval( function(){
    marquee.changeHeading();
}, 700 );

Comments

0

Since you are using jQuery, simplest way to run your code is to replace your last line to line below

var marqueeInterval = window.setInterval($.proxy(marquee.changeHeading, marquee), 700);

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.