同时将JavaScript对象扩展为init

时间:2013-03-11 19:59:49

标签: javascript oop

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

参加以下课程:

var class = {}

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

E.g。现在扩展init:

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

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

3 个答案:

答案 0 :(得分:2)

您可以使用也调用覆盖函数的函数覆盖该函数:

(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));

答案 1 :(得分: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);
    };
}());

答案 2 :(得分:0)

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

Live at 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();