扩展功能 - 合并两个功能? [英] Extend a function - merge two functions?
问题描述
我现在处于一个新的领域,我有一段时间没有处理过这种事情。
I am in some new territory now, I haven't worked with this sort of thing in a while.
获得Javascript的最佳方式是什么? class'例如
What is the best way to have a Javascript 'class' for instance
// In the parent instance
function xyz()
{
var x = 1;
}
我想在课堂上设置这个,当用户扩展课程时,我希望他们有效地扩展这个功能。我知道我不清楚,但这是漫长的一天。例如,这是用户的代码。
I want to set this in the class, and when a user extends a class, I want them to effectively be extending this function. I know I'm not being clear, but it's been a long day. This is the user's code for instance.
// In the child instance
function xyz()
{
var y = 2;
}
合并应该导致:
// In the merged instance
function xyz()
{
var x = 1;
var y = 2;
}
我吸错了什么或提出错误的问题?
Am I smoking the wrong stuff or asking the wrong question?
推荐答案
你不能像在那里描述的那样合并函数,但你可以做的是重新定义一个函数来调用它们本身和一个新函数(在原始函数之前或之后)。
You can't 'merge' functions as you describe them there, but what you can do is have one function be redefined to call both itself and a new function (before or after the original).
var xyz = function(){
console.log('xyz');
};
var abc = function(){
console.log('abc');
};
// and, elsewhere, if you want to merge:
var orig = abc;
abc = function(){
orig.call(this, arguments);
xyz.call(this, arguments);
};
如果您不关心执行上下文或者不需要包含(this,arguments)如果被调用的函数是无参数的。但是,如果你想要一个参数化的方法,那么为了清楚说明你可能会做什么,我将其包括在内。
The inclusion of (this, arguments) is not needed if you don't care about execution context or if the called function is parameterless. But I included for clarity of what one might do if you wanted a parameterized method.
这篇关于扩展功能 - 合并两个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!