显而易见的答案是简单地调用invoke
你的getName
方法。如果,无论出于何种原因,您不想这样做,您可以代理klass
之后的方法:
// loop through all properties of klass
for (var i in klass) {
// skip if it's not a custom property, not a function or the invoke function
// (to prevent infinite nested calls)
if(!klass.hasOwnProperty(i) || typeof klass[i] !== 'function'
|| i === 'invoke') {
continue;
}
// add the invoke() method as a proxy to the current method
var old = klass[i];
klass[i] = function () {
klass.invoke.apply(this, arguments);
return old.apply(this, arguments);
};
}
您还可以像这样将所有内容整齐地放在一起:
var klass = (function () {
this.invoke = function () {
console.log('called invoke()');
};
this.getName = function () {
return "called getName()";
};
(function (_this) {
for (var i in _this) {
if (!_this.hasOwnProperty(i) || typeof _this[i] !== 'function'
|| i === 'invoke') {
continue;
}
var old = _this[i];
_this[i] = function () {
_this.invoke.apply(_this, arguments);
return old.apply(_this, arguments);
};
}
})(this);
return this;
})();
console.log(klass.getName());