开发者

JavaScript scopes and object-orientation

开发者 https://www.devze.com 2023-01-26 16:46 出处:网络
What\'s wrong with this—how come the variable foo isn\'t defined f开发者_Go百科rom within onModified() of a Document object?

What's wrong with this—how come the variable foo isn't defined f开发者_Go百科rom within onModified() of a Document object?

function Document() {

    var foo = "dfsadf";

    this.onModified = function() {
        alert(foo);
    };

}

// Does not alert; "foo" doesn't resolve
new Document().onModified();

I'd like to have public methods on Document that reference variables that are somehow private to Document.


Your Document function is clashing with the Document constructor from the DOM.

document instanceof Document; // true

As with any host-object its behavior completely depends on the host environment, and they often can give you unexpected results.

As far I've tested, on Firefox you are not able to replace its value, therefore I would recommend you to either, rename your function, or, declare it on other scope.

0

精彩评论

暂无评论...
验证码 换一张
取 消