2017-12-02 11 views
0

オリジナルモーダル奇妙な関数の動作 - JavaScriptの

私は普遍的なappオブジェクトを使用します。この空のオブジェクトには、必要に応じて関数を追加します。問題は、いくつかの関数がappオブジェクト内の他のすべての関数に必要となることです。

私の質問は、作成時にオブジェクト内のすべての関数を定義することなく、大きなオブジェクトを構築する方法です。私はコードの塊を1つの天文学的な長い.jsファイルを持たないように分割したいと思います。ここで私が面白い発見何かがある

モーダル

更新

var app = { 
    tow: function() { 
    return true; 
    }, 
    one: function() { 
    return this.tow(); 
    } 
}; 

// app.one() => returns true 

は私の元のコードの簡単な例があります。私はprototypeモーダルで遊んでいて、奇妙なことを発見しました。このモデルを使用すると、他の追加機能を呼び出すことができる機能を追加できます。しかし、イベントリスナーを作成すると、コードを実行できなくなります。誰がこれがなぜなのか説明できますか?予想外の結果に

修正コード:

function modal() {} 

modal.prototype.one = function() { 
    return this.two(); 
}; 

modal.prototype.two = function() { 
    return "cool"; 
}; 

modal.prototype.init = function() { 
    document.getElementById('go') 
    .addEventListener("click", this.one); 
} 

var app = new modal(); 
app.init(); 

// app.one() => returns true 
// event listener => returns "TypeError: this.two is not a function" 

JSBIN:あなたが行ったようにhttps://jsbin.com/vureruziza/edit?js,console,output

+0

投稿ごとに1つの質問のみをお願いします。 – Bergi

+0

"*作成時にオブジェクト内のすべての関数を定義することなく、大きなオブジェクトを構築するにはどうすればいいですか?*" - あなたは必要ありません。まだ割り当てられていない他の関数を使用する関数を作成できます。すべてが作成される前に、実際にそれらの関数のどれかを呼び出すべきではありません。 – Bergi

答えて

0

this.oneと呼ばれてはいない、あなたのオブジェクトに、addEventListenerを機能を指します。この機能は、このコンテキストではなく、ウィンドウのコンテキストが必要になります。この原因と問題

modal.prototype.init = function() { 
    var self = this; 
    document.getElementById('go') 
    .addEventListener("click", function(){ 
     self.one() 
    }); 
} 
0

バインドにクリック機能を解決します。次にクリックハンドラでthis.one関数を呼び出します。

function modal() {} 
 

 
modal.prototype.one = function() { 
 
    return this.two(); 
 
}; 
 

 
modal.prototype.two = function() { 
 
    return "cool"; 
 
}; 
 

 
modal.prototype.init = function() { 
 
    document.getElementById('go') 
 
    .addEventListener("click", function(e){ 
 
     console.log(this.one()) 
 
    }.bind(this)); 
 
    
 
/* 
 
The following wil also be called but your return value 
 
of your this.one function won't be captured. But your code will run. 
 

 
    .addEventListener("click", this.one.bind(this)); 
 
    
 
Try replacing it with the above and put a debugger statement in this.one 
 
and see that the code will actualy be ran, just not captured to output. 
 
*/ 
 
} 
 

 
var app = new modal(); 
 
app.init(); 
 

 
// app.one() => returns true 
 
// event listener => returns "TypeError: this.two is not a function"
<div id="go">go</div>

0

使用ES6脂肪矢印機能。

modal.prototype.init = function() { 
    document.getElementById('go') 
    .addEventListener("click",() => this.one()); 
} 

編集は - -

modal.prototype.one = function() { 
    console.log(this); 
    return this.two(); 
}; 

あなたが最も可能性が高いでしょう - あなたが問題をデバッグしたい場合、あなたはそのような機能oneでちょうどconsole.logthis値可能性として以下のmodal.prototype.initを更新しますwindowオブジェクトです。確かにmodalオブジェクトは表示されません。