为什么我的JS对象看不到自己的函数?

时间:2013-03-16 01:35:08

标签: javascript object

http://jsfiddle.net/totszwai/WvbPn/2/

function DialogBox() {
    this.__DEBUGGING__ = false;

    DialogBox.debug = function (b) {
        this.__DEBUGGING__ = b;
    };

    DialogBox.test = function (b) {
        alert("hello worodl");
    };
};


$(document).ready(function () {
    dialogbox = new DialogBox();
    dialogbox.test();
});

我无法弄清楚我在那里做错了什么。我用

试了一下
DialogBox.prototype.test
DialogBox.test
test

我试图让它在内部调用自己的函数时,我不需要一直放this ...例如:this.test()

更新 还有一种方法可以在调用私有函数时到处输入“this”吗?通常我只是编写一次性使用的简单全局函数,但现在我正在尝试编写不同的东西,并且我将在我的类中调用这些私有函数。所以我试图避免在任何地方使用“this”...更不用说它使代码可读性非常差。

例如在Java(而不是JS)中,您无需在任何地方输入“this”。

1 个答案:

答案 0 :(得分:4)

快速修复:

在DialogBox定义中,使用this.定义其方法:

http://jsfiddle.net/AaronBlenkush/WvbPn/4/

function DialogBox() {
    this.__DEBUGGING__ = false;

    this.debug = function (b) {
        this.__DEBUGGING__ = b;
    };

    this.test = function (b) {
        alert("hello worodl");
    };
};


$(document).ready(function () {
    dialogbox = new DialogBox();
    dialogbox.test();
});

如需全面解答:

StackOverflow的答案太多了。

有关此主题的详细阅读,请参阅Addy Osmani的书Learning JavaScript Design Patterns,特别是关于构造函数模式和周围部分的部分。

相关问题