Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript "static imports"

Is there anything in javascript that is the equivalent of java static imports? For example, if I have a Math class that looks like

com.example.Math = function() {

   function1(...) {}
   function2(...) {}

}

Now some of these functions are naturally chained together such that the output to one is the input to another. I can do something like

com.example.Math.function2(com.example.Math.function1());

This is a little ugly looking, and I would really like to do something like:

function2(function1())

But I don't want to put function1 and function2 in the global namespace. Is this possible?

like image 453
Jeff Storey Avatar asked Mar 14 '26 17:03

Jeff Storey


2 Answers

Yes, there is. It's called with.

with (com.example.Math) {
    function2(function1());
}

That said:

Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.

For example:

var m = com.example.Math;
m.function2(m.function1());
like image 57
Matt Ball Avatar answered Mar 16 '26 07:03

Matt Ball


How about:

var Math = com.example.Math;

and then:

Math.fn1( Math.fn2(...) );

I'm assuming of course that your code is not global code. (If you're not familiar with the concept of avoiding global code in JS, read about the module pattern.)


You can go one step further:

var Math = com.example.Math,
    func1 = Math.func1,
    func2 = Math.func2;

and then:

func1( func2(...) );
like image 28
Šime Vidas Avatar answered Mar 16 '26 07:03

Šime Vidas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!