如何在另一个函数中覆盖 JS 函数? [英] How can I override a JS function inside another function?

查看:37
本文介绍了如何在另一个函数中覆盖 JS 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于覆盖另一个函数内部的 js 函数的位置.

Am in a position of overriding a js function which is inside another function.

例如:

function parentMethod(){
   function someOtherMethod(){
      alert("Am someone")
   }
   function childMethod(){
      alert("Am Child")
   }
   childMethod()
}

childMethod = function(){
      alert("Am Child New")
   }

实际上我想覆盖sharepopint提供的开箱即用js scirpt的一个子函数.如果我覆盖了parentMethod,它工作正常,但它会产生1300行代码重复因为我们实际上正在覆盖许多可用功能之一.

Actually I want to override a sub function of the out-of-the-box js scirpt provided by sharepopint.If I override parentMethod it is working correctly but it will produce 1300 lines of code duplication since we are actually overriding one of the many available functions.

如何在不重复代码的情况下实现它.任何帮助将不胜感激.

How can I achieve it without code duplication. Any help would be greatly appreciated.

提前致谢.

推荐答案

除非正确定义了父函数,否则您提到的 childMethod 不能在父范围之外访问,即您尝试访问的 childMethod 未链接到父母.例如

The childMethod you mentioned is not accessible outside the scope of the parent unless the parent function is defined properly i.e. the childMethod you are trying to access is not linked to the parent. e.g.

var parentMethod = function (){
   this.someOtherMethod = function (){
      alert("Am someone")
   }
   this.childMethod = function(){
      alert("Am Child")
   }
}

在父类的当前状态下没有正确的方法来实现这一点,但是为了一个工作示例,我制作了一个工作小提琴.https://jsfiddle.net/eaqnnvkz/

There is no proper way of achieving this with the current state of the parent class however I made a working fiddle for the sake of a working example. 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 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆