0

あなたの時間と助けに感謝しきれません! ほぼ2日間検索しましたが、正確な答えが見つかりません。始める:

私は常にオブジェクト リテラル表記法を使用してオブジェクトを作成してきました。ただし、最近、同じオブジェクトの複数のインスタンスを作成する必要がある状況に遭遇しました。私が作成しようとしているのは「コンストラクター関数」だと思います:

複数の「ウィンドウ」オブジェクトを作成する機能が必要です。

var window1 = new Window();
var window2 = new Window();
var window3 = new Window();

メソッドを次のように整理できる機能が必要です。

window1.errorMessage.show();
window2.errorMessage.hide();
window3.errorMessage.hide();

次のようなものの代わりに:

window1.showErrorMessage();
window2.hideErrorMessage();
window3.hideErrorMessage();

ウィンドウ オブジェクトをリテラル表記で作成する方法の例:

var Window = {
    id: null,
    
    init : function(id) {
        this.id = id;
    },

    errorMessage : {
        show : function(message) {
            // jquery that will simply take the id of this window,
            //  find the errorMessage html element within the window,
            //  insert the "message" and show it.
        },
    
        hide : function() {
            // jquery that will simply take the id of this window,
            //  find the errorMessage html element within this window and hide it.
        }
    }
}

コンストラクター関数とプロトタイピングを使用してウィンドウ オブジェクトを構築する方法の例:

function Window(id) {
    this.id = id;

    this.errorMessage = function() {}
}

Window.prototype.errorMessage = function() {}

Window.errorMessage.prototype.show = function(message) {
    // jquery that will simply take the id of this window,
    //  find the errorMessage html element within the window,
    //  insert the "message" and show it.
}

Window.errorMessage.prototype.hide = function() {
    // jquery that will simply take the id of this window,
    //  find the errorMessage html element within this window and hide it.
}

次のコードを実行しようとすると:

var window1 = new Window();

window1.errorMessage.show('An error message');

(最終的には、次を使用して呼び出したいと思います:)

this.errorMessage.show('An error message');

Firefox から次のコンソール エラーが表示されます。

  • TypeError: Window.errorMessage は定義されていません
  • TypeError: Window.errorMessage.show は関数ではありません



助けてくれてどうもありがとう。それは有り難いです。

4

2 に答える 2

2

prototype継承を行う場合にのみ使用する必要があります。継承を行っていないので、今は忘れてくださいprototype

それぞれWindowに のインスタンスがありますErrorMessage。だから私はそれを次のように書きます:

function Window(id) {
  this.id = id;
  this.errorMessage = new ErrorMessage();
}
function ErrorMessage() {
   this.show = function () {};
   this.hide = function () {};
}
var window1 = new Window();
window1.errorMessage.show();
于 2013-08-28T17:11:23.027 に答える