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)

4

1 回答 1

1

第一次调用.GetHTML()它会返回一些 HTML,但在这个过程中Object.defineProperty调用会用一个没有 value的新属性覆盖.GetHTML方法。

因此,在第二次调用时你得到一个错误也就不足为奇了,因为.GetHTML那时的值为undefined.

如果您的代码的目的是确保它GetHTML不可枚举,请使用以下代码直接将方法添加到Wbook.prototype并(自动)将其设置为不可枚举:

Object.defineProperty(Wbook.prototype, 'GetHTML', {
    value: function() {
        ...
    }
});
于 2013-10-16T18:33:25.633 回答