2017-02-08 28 views
1

上一個覆蓋另一個函數內部的js函數的位置。如何重寫另一個函數內的JS函數?

例如:

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

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

其實我要重寫我重寫parentMethod是否正常工作由sharepopint.If提供的外的開箱JS scirpt的子功能,但它會產生1300因爲我們實際上覆蓋了許多可用函數中的一個,所以代碼重複。

如何在沒有代碼重複的情況下實現它? 任何幫助將不勝感激。

在此先感謝。

回答

2

您提到的childMethod無法在父級範圍之外訪問,除非父級功能已正確定義,即您嘗試訪問的childMethod未鏈接到父級。例如

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

有一個與父類的當前狀態,實現這一目標,但是我做了一個工作搗鼓工作示例的緣故沒有正確的方法。 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(); 
+0

謝謝你的回答:)。問題是,實際上父方法不是由我寫的。它是指的是共享點開箱即用腳本文件。所以我不能改變父方法。 – Unknown

0

不幸的是,除非編寫腳本來將子函數附加到可訪問範圍,否則它不能被有選擇地覆蓋。默認情況下,函數中的函數不是單獨可訪問的。

可能會嘗試的一種頗爲冒險的方式是通過parentMethod.toString()獲取parentMethod()的源代碼,然後使用正則表達式替換子方法,然後將該函數的原始版本替換爲已更改的版本使用eval()。這可能不是一個長期的解決方案,我個人會勸阻它,但理論上它會達到要求的效果。

相關問題