perform function that is within a Javascript Extract

Asked

Viewed 55 times

2

1 answer

4


It will not be possible to access all internal functions, but you can access what is exported from that module.

Explanation: When you have a structure like:

(function (exports) {
    function a() {
        alert('oi');
    }
})(escopo);

that function a is within a scope that does not allow to be accessible outwards. This uses a lot to limit the scope of functions and not pollute the global space with variable names.

Notice that in that file you mentioned:

exports.JSEncrypt = JSEncrypt;
})(JSEncryptExports);

i.e., it exports to the object/variable that is passed to JSEncryptExports.

So some functions you will never have access to, but the methods that are spouses you can find in JSEncryptExports. And that way you can reuse the code.

It’s commum to use like this when you want to export to global space:

(function(global){
     // código A aqui...
     global.meuModulo = function(a, b, c){
         // código que tem acesso aos métodos defenidos no "código A"
     }
})(typeof exports != 'undefined' ? exports : window);

This way works both in Nodejs and in the Browser.

  • there is no way I can adapt this code to work as I want? Like remove everything from the scope or pass the variable for me to use on the outside

  • 2

    @user3163662 you can join in the last row before exports.JSEncrypt = JSEncrypt; a way to export this function -> exports.BigInteger = BigInteger; and then use JSEncryptExports.BigInteger outside this module.

  • 2

    +1 This is why I hate encapsulation, people abuse a lot... It’s okay to hide internal details of an implementation, but why hide an entire library?!

  • @mgibsonbr is very bad, see I am using this library and another that use THE SAME FUNCTIONS of it but I can not use because of this encapsulation, there is this unnecessary code amuntuado, hate.. Thank you Sergio!

  • 2

    @mgibsonbr It seems to have been very wrong. The indentation indicates that IIFE and Exports were added later, in a hurry. It would be right to declare dependencies (in a package.json, in npm format) and use requires, rather than encapsulating external libraries.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.