在调用另一个方法之前或之后调用Javascript fire方法

javascript fire method before or after another method is called

本文关键字:方法 调用 Javascript fire 或之后 另一个      更新时间:2023-09-26

我想知道让这个概念起作用的常见方法是什么:

function Abc () {
  var beforeMethod = function (e) {
    console.log(e);
  };
  this.before('bob ana', beforeMethod);
}
Abc.prototype.ana   = function () { console.log('ana'); }
Abc.prototype.bob   = function () { console.log('bob'); }
Abc.prototype.maria = function () { console.log('maria'); }
//
var abc = new Abc();
abc.ana();

应该在调用bobana之前调用beforeMethod

快速:

需要测试和安全,但我认为它做的伎俩!我不明白你的e是什么意思,所以我把调用的方法名放在里面!

var el = document.getElementById('debug');
var $l = function(val) {
    console.log(val);
    el.innerHTML = el.innerHTML + '<div>' + val + '</div>';
  };
//___________________________________________________________________
var Before = function( methods , func , context){
  methods.split(' ').map(function(m){
    var ori = context[m];
    if(ori){
      context[m] = function(){
        func.call(context , m);
        return ori.apply(context , arguments);
      };
    } 
  });
};
var Abc = function () {
  var beforeMethod = function (e) {
    $l('from beforeMethod : ' + e);
  };
  Before('bob ana ', beforeMethod , this);
};
    
    Abc.prototype.ana   = function () { $l('from ana '); };
    
    Abc.prototype.bob   = function () { $l('from bob '); };
    
    Abc.prototype.maria = function () { $l('from maria '); };
    
    var abc = new Abc();
    
    abc.ana();
    abc.maria();
    abc.bob();
<div id='debug'>Debug
  <div>

我认为这样做的方法是将旧的原型函数保存在属性中。

function Abc() {
    this.oldana = this.prototype.ana;
    this.oldbob = this.prototype.bob;
    this.prototype.ana = function(e) {
        console.log(e);
        this.oldana();
    }
    this.prototype.bob = function(e) {
        console.log(e);
        this.oldbob();
    }
}