Spencer Mark
Spencer Mark

Reputation: 5311

Javascript Object Prototype TypeError: ... is undefined

I'm have a problem with calling the method in the prototype, which returns:

TypeError: this.backgroundImagesReplace(...) is undefined

this.backgroundImagesReplace(data)

My code looks like the following:

var Template = function() {};

Template.prototype = {

    backgroundImagesReplace : function(data) {

        var defer = $.Deferred();

        // some code that resolves the deferred object
        defer.resolve(data);

    },

    replace : function(data, callback) {

        this.backgroundImagesReplace(data)
            .done(this.replaceContent)
            .done(this.replaceElement)
            .done(this.replaceAttribute)
            .done(systemObject.executeCallBack(callback));

    },

    init : function() {

        this.replace([], function() {

            console.log('here');

        });

    }

};

var TemplateObject = new Template();
TemplateObject.init();

Any idea what might be causing it?

Upvotes: 0

Views: 533

Answers (2)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

You've forgotten to return the object in your backgroundImagesReplace function. While you could return the Deferred object directly, it would be advisable to return a Promise object instead, as that's more suitable for passing to other objects/functions. Deferred objects should be kept private as their state can be directly changed, while it is much more difficult to accidentally change the state through a Promise object. You can do that by doing the following:

backgroundImagesReplace : function(data) {

    var defer = $.Deferred();

    // some code that resolves the deferred object
    defer.resolve(data);

    return defer.promise();
},

This gives you that TypeError as your code is attempting to access a property of undefined, which (of course) will not do what you expected it to do.

Upvotes: 3

Phil H
Phil H

Reputation: 20131

Your method backgroundImagesReplace does not return anything. So the result of calling it is undefined, on which you are trying to call .done().

Upvotes: 0

Related Questions