p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Professional JavaScript for Web Developers 3rd edition (http://p2p.wrox.com/forumdisplay.php?f=669)
-   -   How does the return function in createComparisonFunction() get it's parameters? (http://p2p.wrox.com/showthread.php?t=98619)

MrAnalogy February 14th, 2016 03:47 PM

How does the return function in createComparisonFunction() get it's parameters?
On line 4 a function is declared which is RETURNED to the calling function.

How do Object1 and 2 get defined/set?

This is from Chapter 5 of Professional javascript... 3rd edition.


<script type="text/javascript">
            function createComparisonFunction(propertyName) {
                return function(object1, object2){
                    var value1 = object1[propertyName]; //how do Object1 and object2 get set?
                    var value2 = object2[propertyName];
                    if (value1 < value2){
                        return -1;
                    } else if (value1 > value2){
                        return 1;
                    } else {
                        return 0;
            var data = [{name: "Zachary", age: 28}, {name: "Nicholas", age: 29}];
            alert(data[0].name);  //Nicholas
            alert(data[0].name);  //Zachary       

MrAnalogy February 15th, 2016 09:01 PM

.sort accepts a Function() as a parameter
See specs on array.sort()

That sort function should have two object parameters (a,b below) which (I assume) just get "magically"* passed to that function by the .sort function.

As touched on already, array.sort() accepts an optional parameter in the form of a function reference (lets call it sortfunction). The format of this function looks like this:

function sortfunction(a, b){
//Compare "a" and "b" in some fashion, and return -1, 0, or 1

* I'm new to .js And:
Any sufficiently advanced technology is indistinguishable from magic.

All times are GMT -4. The time now is 06:13 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.