2017-10-10 131 views
-1

我有這樣的腳本,我需要注入插入JavaScript代碼放到匿名函數範圍

! function(e) { 
    function doSomething() 
    { 
    } 
} 

基本上我去DoSomething的,當我的代碼是通過函數對象調用的引用,但我需要勾到doSomething,所以我需要一個id的原始引用。由於doSomething是在匿名函數中聲明的,所以我無法得到它。問題是,我可以以某種方式將代碼注入匿名函數,Greesemonkey或任何其他工具的範圍。

+0

「注入」是什麼意思?你是否試圖製作一個在特定頁面上操作JS的用戶腳本/瀏覽器擴展?是的,你可以做任何你想做的事情,但是你不能僅僅通過引用來改變'doSomething'。 – Bergi

+0

是的,我正在編寫一個用戶腳本,並希望與網頁上的某些功能掛鉤。爲此,我需要將原始引用更改爲匿名函數範圍內的函數。 – user1617735

+0

你最好的選擇是攔截腳本加載,更改它的源代碼並評估它。 – Bergi

回答

0

Javascript並不容易從範圍內獲取值。

您可以在更廣的範圍內聲明doSomething

function doSomething() { 
    // ... 
} 
function func(e) { 
    doSomething(); // This works! `func` has a reference to `doSomething` 
} 

doSomething(); // This also works! `doSomething` is declared in this scope. 

您還可以從內部範圍的返回值!例如:

function func(e) { 
    function doSomething() { 
     // ... 
    } 

    // Note that we are not invoking `doSomething`, we are only returning a reference to it. 
    return doSomething; 
} 

var doSomething = func(/* some value */); 

// Now you got the reference! 
doSomething(); 

有時已經需要返回另一個值你的外在功能:

function func(e) { 
    function doSomething() { /* ... */ } 
    return 'important value!!'; 
} 

在這種情況下,我們仍然可以返回doSomething,與原來的值一起:

function func(e) { 
    function doSomething() { /* ... */ } 
    return { 
     value: 'important value', 
     doSomething: doSomething 
    }; 
} 

var funcResult = func(/* some value */); 
var originalValue = funcResult.value; 
var doSomething = funcResult.doSomething; 

// Now we have the original value, AND we have access to `doSomething`: 
doSomething(); // This works 
+0

那麼我需要鉤住該範圍內的函數,這意味着我仍然需要修改該函數的原始引用,因爲它被該範圍內的多個其他函數調用。如果我用全局函數覆蓋它,我只會實現所有那些現在正在調用我的函數,但我仍然需要調用我需要鉤住的原始函數。 – user1617735

+0

我列出的其他方法呢?只需在返回值中包含'doSomething'? –

+0

我無法訪問內部範圍,這是整個問題。 – user1617735