views:

46

answers:

3

I have a very simple bit of code (relies on jQuery):

var dom_builder = function() {

    this.table = function(elem,attributes) {
        return $("<table>").attr(attributes).appendTo(elem);
    }

};

console.log(dom_builder.table);

Now when I try to run it I get the following error: Uncaught TypeError: Object # has no method 'table'

I cannot for the life of me figure out why I get this error. I have used methods this way countless times before, without any issues..

Any ideas?

+1  A: 
console.log(new dom_builder().table);
Anurag
you need parenthesis, like `console.log(new dom_builder().table())` for this to work
cambraca
@cambraca Anurag's syntax is valid. It's all about what you're trying to demonstrate, and I think he wanted to show that the function does exist using this syntax.
Adam Backstrom
@Adam Backstrom it's valid, but it won't work as expected. It will return the function, instead of the function result, which is what is required, no?
cambraca
Thanks! Totally my own fault, that'll teach me for copying old code.
Nathan
+2  A: 

Try this

var dom_builder = {

    "table": function(elem,attributes) {
        return $("<table>").attr(attributes).appendTo(elem);
    }

};
cambraca
Nice, totally different approach and it works without having to initiate the function as recommended below :) Nice
Nathan
A: 

dom_builder.table doesn't exist until the function is run.

console.log(dom_builder.table); // undefined
d = new dom_builder();
console.log(d.table); // function(elem, attributes) { ... }
Adam Backstrom