SeaSky
SeaSky

Reputation: 1312

Constructor for Javascript Objects

I am trying to create a JAvascript Object with a constructor and 2 methods. I am getting errors when I try to use the following code, what am I doing wrong? Specifically, it wont allow me to define the constructor function as shown below.

var Feed = {

    templateDOM: '',

    function(tDOM) {
        this.templateDOM = tDOM;
    },

    loadFeed: function(feedPage, feedsPerPage) {
        ...
    },

    showFeed: function(data, tDOM, destination) {
        ...
    }
};

Upvotes: -1

Views: 46

Answers (2)

Christos
Christos

Reputation: 53958

I don't think that you approach can take you where you want. In your case you make use of an object literal. How are you going to make use of constructor, when you have already created an object?

I think that the following would be more suitable:

// Define a cosntructor
function TemplateDom(tDom){
     this.templateDOM = tDOM;
}

and then add to the prototype of you constructor the methods:

// Add to the prototype of your constructor the following two functions.
// So each object that will be created using this constructor would have
// defined also those two methods.
TemplateDom.prototype.loadFeed = function(feedPage, feedsPerPage) {
    ...
};

TemplateDom.prototype.showFeed = function(data, tDOM, destination) {
    ...
};

Then you can create an object like below:

var templateDom = new TemplateDom("here you pass a dom value");

and you can use the functions loadFeed and showFeed as simple as

templateDom.loadFeed("feedpage value","feedsperpage value");
templateDom.showFeed("data value","tDom value","destination value");

Upvotes: 1

Quentin
Quentin

Reputation: 943556

You aren't creating a constructor function at all here. It is a plain object, only you forgot to provide a property name for the second value in it.

If you wanted to create a constructor function, it would look more like this:

function Feed(tDOM) {
    this.templateDOM = tDOM;
}

Feed.prototype.loadFeed = function loadFeed(feedPage, feedsPerPage) {
};

Feed.prototype.showFeed = function showFeed(data, tDOM, destination) {
};

Which you can then invoke like:

var my_feed = new Feed("some value");
myFeed.loadFeed("some value", "some other value");

Upvotes: 2

Related Questions