javascript原型 - 添加回调

时间:2012-07-20 19:00:53

标签: javascript jquery

我正在使用javascript揭示原型模式,我想添加一个回调。我正在尝试这样的事情:

http://jsfiddle.net/Qyhrb/2/

  var Refinements = function () { };

  Refinements.prototype = function () {
    Init = function () {
      $('.btn').click(Callback);
    },
    Callback = function(){
      alert('default function');
    };
    return { Init: Init, Callback : Callback };
  }();


   var refinements = new Refinements();
   refinements.Callback = function(){ alert('new method'); };
   refinements.Init();

基本上我想做的是将回调传递给对象,并在事件发生时引发回调。

4 个答案:

答案 0 :(得分:5)

    Init = function () {
        var refinement = this;
        $('.btn').click(refinement.Callback || Callback);
    },

Fiddle

答案 1 :(得分:1)

var Refinements = function() {};

Refinements.prototype = function() {
  return {
    init: function() {
      $('.btn').click(this.callback);
    },
    callback: function() {
      alert('default function');
    }
  }
}();


var refinements = new Refinements();
refinements.callback = function() {
  alert('new method');
};
refinements.init();

答案 2 :(得分:1)

当我分离原型函数并删除return { Init: Init, Callback : Callback };时,一切似乎都正常。

function Refinements() {}

Refinements.prototype.Init = function() {
    $('.btn').click(this.Callback);
};

Refinements.prototype.Callback = function() {
    alert('default function');
};


var refinements = new Refinements();
refinements.Callback = function(){ alert('new method'); };
refinements.Init();​

http://jsfiddle.net/Qyhrb/8/

答案 3 :(得分:1)

Foobar = function() {
    this.callBack = function() {
        alert("Default method");
    };
}

Foobar.prototype = {
    Init: function() {
        var self = this;
        $(".btn").click(function() {
            self.callBack.call();
        });
    }
};

var foobar = new Foobar();
foobar.Init();
foobar.callBack = function() {
    alert("Boo!");
};