AlvaroFG
AlvaroFG

Reputation: 472

TypeError when using Jquery and Object property function

I'm getting an error when using jquery and I would like to know its cause:

here is part of my code

function Wbook(name){
this.name = name;
}

Wbook.prototype.GetHTML = function() {

Object.defineProperty(this, "GetHTML", {enumerable : false,
                           configurable : true});

var html ='<h1>TEST1</h1>';
return html;
};

var rs = {};

rs.WB = new Wbook('test1');

var foo = rs.WB.GetHTML(); 
$(foo).appendTo('div#id1'); // This works

$(rs.WB.GetHTML()).appendTo('div#id1'); 
// This doesn't work >> TypeError: rs.WB.GetHTML is not a function

I can also getting to work if I comment the Object.defineProperty section, so I'm suspecting this might have to do with the enumerability, but I'm not sure of it

//Edit: While creating Jfiddle, I notice rs.WB.GetHTML() is always failing the second time it runs :-/. (It works fine if I comment the Object.defineProperty section)

Upvotes: 1

Views: 168

Answers (1)

Alnitak
Alnitak

Reputation: 339786

The first time you call .GetHTML() it's returning some HTML, but in the process the Object.defineProperty call is overwriting the .GetHTML method with a new property that has no value.

It's therefore unsurprising that on the second invocation you get an error because the value of .GetHTML by then is undefined.

If the intent of your code is to ensure that GetHTML is not enumerable, use the following code which directly adds the method to Wbook.prototype and (automatically) sets it non-enumerable:

Object.defineProperty(Wbook.prototype, 'GetHTML', {
    value: function() {
        ...
    }
});

Upvotes: 1

Related Questions