[英]How to supplement object function from outside
var object = {}; //lots of stuff in here
var func = object.dosome;
object.dosome = function(a,b) {
func(a,b);
//someth else here i need to add
}
This works but ugly. 这工作,但丑陋。
So is there a way to supplement object.dosome method, without creating a new variable containing it's function? 那么有没有一种方法可以补充object.dosome方法,而无需创建一个包含其功能的新变量?
Some sort of parent.dosome? 某种parent.dosome?
maybe create a class Object and define in its protoype the dosome() method. 也许创建一个Object类并在其原型中定义dosome()方法。
var Object = new function() {}; //lots of stuff in here
Object.prototype.dosome = function(a,b) {
func(a,b);
}
//and then
var myObject = new Object();
I think you should read a little about JS OOP . 我认为您应该阅读一些有关JS OOP的知识 。 ES6 adds some nice syntactic sugar that can help you achieve what you want in fewer lines of code. ES6添加了一些不错的语法糖,可以帮助您用更少的代码行实现所需的功能。 Read more here . 在这里阅读更多。
However, if you don't want to have problems with the prototype chains, here's a simpler way of achieving what you want: 但是,如果您不希望原型链出现问题,这是一种实现所需目标的简单方法:
function chain (baseFunc, func) {
return function () {
var args = [].slice.call(arguments, 0);
args.unshift(baseFunc);
return func.apply(this, args);
};
}
Usage: 用法:
var obj = {
doSome: function (a, b) { return a + b; }
};
obj.doSome(4, 5); // 9
obj.doSome = chain(obj.doSome, function (baseFunc, a, b) {
var result = baseFunc(a, b);
return result + 10;
});
obj.doSome(4, 5); // 19
You can go one step further and get rid of the assignment: 您可以再走一步,摆脱作业:
function extend (instance, method, func) {
instance[method] = chain(instance[method], func);
}
extend(obj, "doSome", function (baseFunc, a, b) {
var result = baseFunc(a, b);
return result + 2;
});
obj.doSome(4, 5); // 21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.