0

扩展函数的最佳方法是什么,以便在调用它时也调用新的扩展类。

参加以下课程:

var class = {}

class.init = function(){
 //do something
};

例如,现在扩展 init:

class.init.prototype.extend = function(){
 console.log("hey look at me, I get called too!");
}

这里的想法是,当调用 class.init() 时,我们希望扩展类也被自动调用。目标是扩展类,例如将点击事件绑定到链接,但不修改原始函数中的任何内容。

4

3 回答 3

2

You can overwrite the function with one that also calls the overwritten one:

(function (old) {
    class.init = function() {
        console.log("hey look at me, I get called before!");
        var result = old.apply(this, arguments);
        console.log("hey look at me, I get called after!");
        return result;
    };
}(class.init));
于 2013-03-11T20:05:30.467 回答
1

您可以重新分配class.init给调用原始函数和新函数的代理函数。

像这样的东西:

var class = {}

class.init = function(){
 //do something
};

(function(){
    var _old = class.init;
    class.init = function(){
        console.log("hey look at me, I get called too!");
        return _old.apply(this, arguments);
    };
}());
于 2013-03-11T20:04:22.567 回答
0

一种更通用的extend方法,可以扩展任何方法,而不仅仅是 init:

住在JSBin

function Klass(name){
  this.name = name;
  this.staticMethod = function(){console.log('static method at Klass');};
}

Klass.prototype.someMethod = function(){console.log('Klass.someMethod');};

Klass.extend = function(extention){
  function extendMethod(method1, method2){
    var args = arguments;
    var contex = this;
    return function(){
      method1.apply(contex, args);
      method2.apply(contex, args);
    };
  }

  var proto = new Klass();
  var Extended = function(){Klass.apply(this, arguments);};
  for(var key in extention){
    if(typeof proto[key] === 'function' && typeof extention[key] === 'function'){
      var oldMethod = proto[key];
      proto[key] = extendMethod(oldMethod, extention[key]);
    }
  }
  Extended.prototype = proto;
  return Extended;
};




var ExKlass = Klass.extend({
  someMethod: function(){
    console.log('ExKlass.someMethod');
  }
});


var k = new Klass();
var ek = new ExKlass();

k.someMethod();
ek.someMethod();
于 2013-03-11T20:42:02.837 回答