简体   繁体   中英

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)

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() {
        ...
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM