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()
更新: 还有一种方法可以在调用私有(private)函数时不在任何地方键入“this”?通常我只编写一次性使用的简单全局函数,但现在我尝试编写一些不同的东西,并且我将在类中的各处调用这些私有(private)函数。所以我试图避免在任何地方使用“this”...更不用说它使代码的可读性非常糟糕。
就像在 Java(而不是 JS)中一样,您不需要在任何地方都键入“this”。
最佳答案
快速修复:
在 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 ,特别是关于构造函数模式的部分以及周边部分。
关于javascript - 为什么我的 JS 对象看不到它自己的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444614/