There is a Test class with the ShowMessage method. I can assign him a new method Message. But how can I add another call to the existing one? I want to join JoinMessage. When you call ShowMessage, a message should appear Test message and then Join message

function Test() { this.ShowMessage = function() { // default method }; } function Message() { alert("Test message"); } function JoinMessage() { alert("Join message"); } var t = new Test(); t.ShowMessage = Message; // ОК t.ShowMessage += JoinMessage; // FAIL t.ShowMessage(); 
  • Not special on js, but something like this should roll: var savedShowMessage = t.ShowMessage; t.ShowMessage = function () {savedShowMessage.apply (this); JoinMessage.apply (this); }; - VladD

2 answers 2

 function Test() { this.methods = []; this.ShowMessage = function() { for(var i = 0; i < this.methods.length; i++) { this.methods[i](); } }; this.addMethod = function ( method ) { this.methods.push(method); }; } function Message() { alert("Test message"); } function JoinMessage() { alert("Join message"); } var t = new Test(); t.addMethod( Message ); t.addMethod( JoinMessage ); t.ShowMessage(); // можно и через прототипы подсластить и вызовы через apply сделать 

    Just stuff them into an anonymous function in the proper order:

     var t = new Test(); t.ShowMessage = function() { Message(); JoinMessage(); }; t.ShowMessage();