Search code examples
javascriptpixel

pixel.getGreen vs pixel.getGreen()


I'm working on an assignment that uses pixel.getGreen() method. My question is when I try using pixel.getGreen (without the parentheses) I get a different result than when using the method with parentheses. What's the difference between the two?
Here's the code I'm working with:

function swapRedGreen(pixel){ 
    var oldRed = pixel.getRed();
    var oldGreen = pixel.getGreen();
    pixel.setRed(oldGreen); 
    pixel.setGreen(oldRed); 
    return pixel;
}
var image = new SimpleImage("smallhands.png");
print (image);
for (var pixel of image.values()) { 
        pixel = swapRedGreen(pixel); 
    } 
print (image);

I get a pitch black image when I try running the code without the parentheses.


Solution

  • pixel.getGreen() is a function invocation, whereas pixel.getGreen is just accessing the getGreen property of the pixel object, which in this case, should be a function definition. Remember, you can reference a function without invoking it, but the parentheses in JS mean you are calling/invoking the function. Without seeing the library/source you're working with, it should be something like this:

    var pixel = {
       getGreen: function() {
         return 'green';
       }
    };
    console.log(pixel.getGreen) // function() {...}
    console.log(pixel.getGreen()) // 'green'
    

    If that's not what you see, post some more context.