2

EDIT: Apolgies for the duplicate question but searching for " '()' Javascript " yielded no result for me.

Here goes ... I am doing some pixel manipulation on an image in PHP and porting some Javascript logic into PHP to achieve an effect that I have seen on a html5 canvas. The Javascript uses some curves calculation to achieve a "vintage effect". The pixel calculations get called within a loop:

Javascript:

for (var i = (width * height); i >= 0; --i) {

    idx = i << 2;

    // curves
    if (!!_effect.curves) {
        _imageData[idx  ] = _effect.curves.r[ _imageData[idx  ] ]; // r
        _imageData[idx + 1] = _effect.curves.g[ _imageData[idx + 1] ]; // g
        _imageData[idx + 2] = _effect.curves.b[ _imageData[idx + 2] ];  // b

    }


}

The effect.curves object looks like:

var _effect = {
    curves: (function() {
      var rgb = function (x) {
        return -12 * Math.sin( x * 2 * Math.PI / 255 ) + x;
      },
      r = function(x) {
        return -0.2 * Math.pow(255 * x, 0.5) * Math.sin(Math.PI * (-0.0000195 * Math.pow(x, 2) + 0.0125 * x ) ) + x;
      },
      g = function(x) {
        return -0.001045244139166791 * Math.pow(x,2) + 1.2665372554875318 * x;
      },
      b = function(x) {
        return 0.57254902 * x + 53;
      },
      c = {r:[],g:[],b:[]};
      for(var i=0;i<=255;++i) {
        c.r[i] = r( rgb(i) );
        c.g[i] = g( rgb(i) );
        c.b[i] = b( rgb(i) );
      }
      return c;
    })(),  // <-- THIS PART
};

My question is: is the () at the line noted just above telling the curves function to run when it's called from within the _imageData loop?

beingalex
  • 2,416
  • 4
  • 32
  • 71

2 Answers2

3

No, the function call happens as part of the initialization of that object ("_effect"). The value of the property "curves" will be the return value from invoking that function. The function builds up an object and returns it.

In JavaScript, a reference to a function followed by a parenthesized argument list is always a function call.

To make it more clear, imagine that that function had be declared as an ordinary function:

function makeCurves() {
  var rgb = function (x) {
    return -12 * Math.sin( x * 2 * Math.PI / 255 ) + x;
  },
  r = function(x) {
    return -0.2 * Math.pow(255 * x, 0.5) * Math.sin(Math.PI * (-0.0000195 * Math.pow(x, 2) + 0.0125 * x ) ) + x;
  },
  g = function(x) {
    return -0.001045244139166791 * Math.pow(x,2) + 1.2665372554875318 * x;
  },
  b = function(x) {
    return 0.57254902 * x + 53;
  },
  c = {r:[],g:[],b:[]};
  for(var i=0;i<=255;++i) {
    c.r[i] = r( rgb(i) );
    c.g[i] = g( rgb(i) );
    c.b[i] = b( rgb(i) );
  }
  return c;
}

Then the initialization would look like:

var _effect = {
  curves: makeCurves()
};
Pointy
  • 405,095
  • 59
  • 585
  • 614
3

It means the function is being called immediately after being created and being assigned to the curves variable.

QBM5
  • 2,778
  • 2
  • 17
  • 24