I'm working on dividing a working page script between the page/content script and an extension background script; and because a communication port doesn't have a return message that functions like a promise, such that the content script code can wait for a promise in the background script to complete before processing the next desired step, I've been using the communication port to invoke a function in the content script by adding functions to an object. That has worked well and permits the building of a promise.then
chain in the content script that waits for the background script promise to resolve/reject. Things are a little different, however, when doing something similar for moving the indexedDB databases from the page to the extension.
I want to do something like this in the content script.
var f = new Object();
f.db_event_1 = function()
{
// Prepare data.
// Declare functions for background script to invoke in content script
// for oncomplete and onerror/onabort events.
f.db_event_1_.complete = function() { };
f.db_event_1_.error = function() { };
// Communicate with background script, passing data, database name, object store
// names, etc. and invoke database transaction in the background script.
// Wait (not an asyc function wait) for background script to invoke either of the
// above two functions based upon whether the transaction succeeds or fails.
};
I don't fully grasp function variable scope and performed some simple tests to determine how variables declared in a function are "remembered" by functions declared within that function when later invoked. For example, I don't understand why f.func_outer.inner
"remembers" that x was 3 and y was 5 when it was declared.
Can it be relied upon that f.func_outer.inner
will always "remember" variables in this manner?
If the variables are large in size, should they be set to null at the close of func_outer.inner
in order to break all variable references to avoid potential memory leaks?
Thank you.
var f = new Object();
f.func_outer = function( x )
{
console.log( 'func_outer x = ' + x + ', y = ' + y );
f.func_outer.inner = function()
{
console.log( 'func_outer.inner x = ' + x + ', y = ' + y );
};
};
f.func_outer( 3 ); // logs func_outer x = 3, y = 5.
f.func_outer.inner(); // logs func_outer.inner x = 3, y = 5.