1

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)

0

1 Answer 1

1

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() {
        ...
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

and this override is happening in the Object.defineProperty(this, "GetHTML", {enumerable : false,configurable : true}); section right? If so, is there a way to just add the enumerable : false, without overriding the method?
yes - see edit. When you used this it attempted to create a new property on the instance, not modify the existing property on the prototype.
thanks, I got it to work now, just one little thing, there is a typo in the answer: protoype. Thanks again

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.