如何在另一个函数中覆盖 JS 函数?
How can I override a JS function inside another function?
我可以覆盖另一个函数中的 js 函数。
例如:
function parentMethod(){
function someOtherMethod(){
alert("Am someone")
}
function childMethod(){
alert("Am Child")
}
childMethod()
}
childMethod = function(){
alert("Am Child New")
}
实际上我想覆盖 sharepopint.If 提供的开箱即用的 js scirpt 的子函数我覆盖 parentMethod
它工作正常但会产生 1300 行代码重复,因为我们实际上正在覆盖许多可用功能之一。
如何在不重复代码的情况下实现它。
任何帮助将不胜感激。
提前致谢。
不幸的是,除非编写脚本以将 sub-function 附加到可访问的范围,否则无法有选择地覆盖它。默认情况下,函数内的函数不可单独访问。
可能尝试的一种相当骇人听闻的方法是通过 parentMethod.toString()
获取 parentMethod()
的源代码,然后使用正则表达式替换子方法,然后替换使用 eval()
更改版本的函数的原始版本。这可能不是 long-term 解决方案,我个人不鼓励这样做,但理论上它会达到要求的效果。
您提到的 childMethod 无法在父级范围之外访问,除非父级函数定义正确,即您尝试访问的 childMethod 未链接到父级。例如
var parentMethod = function (){
this.someOtherMethod = function (){
alert("Am someone")
}
this.childMethod = function(){
alert("Am Child")
}
}
在父级 class 的当前状态下没有适当的方法来实现此目的,但是为了一个工作示例,我做了一个工作 fiddle。 https://jsfiddle.net/eaqnnvkz/
var parentMethod = {
someOtherMethod: function() {
alert("Am someone")
},
childMethod: function() {
alert("Am Child")
}
};
parentMethod.childMethod();
parentMethod.childMethod = function() {
alert("Am Child New")
};
parentMethod.childMethod();
我可以覆盖另一个函数中的 js 函数。
例如:
function parentMethod(){
function someOtherMethod(){
alert("Am someone")
}
function childMethod(){
alert("Am Child")
}
childMethod()
}
childMethod = function(){
alert("Am Child New")
}
实际上我想覆盖 sharepopint.If 提供的开箱即用的 js scirpt 的子函数我覆盖 parentMethod
它工作正常但会产生 1300 行代码重复,因为我们实际上正在覆盖许多可用功能之一。
如何在不重复代码的情况下实现它。 任何帮助将不胜感激。
提前致谢。
不幸的是,除非编写脚本以将 sub-function 附加到可访问的范围,否则无法有选择地覆盖它。默认情况下,函数内的函数不可单独访问。
可能尝试的一种相当骇人听闻的方法是通过 parentMethod.toString()
获取 parentMethod()
的源代码,然后使用正则表达式替换子方法,然后替换使用 eval()
更改版本的函数的原始版本。这可能不是 long-term 解决方案,我个人不鼓励这样做,但理论上它会达到要求的效果。
您提到的 childMethod 无法在父级范围之外访问,除非父级函数定义正确,即您尝试访问的 childMethod 未链接到父级。例如
var parentMethod = function (){
this.someOtherMethod = function (){
alert("Am someone")
}
this.childMethod = function(){
alert("Am Child")
}
}
在父级 class 的当前状态下没有适当的方法来实现此目的,但是为了一个工作示例,我做了一个工作 fiddle。 https://jsfiddle.net/eaqnnvkz/
var parentMethod = {
someOtherMethod: function() {
alert("Am someone")
},
childMethod: function() {
alert("Am Child")
}
};
parentMethod.childMethod();
parentMethod.childMethod = function() {
alert("Am Child New")
};
parentMethod.childMethod();