JavaScript MiscellanyProperties of functionsThe for...in loopGlobal and local variablesMethods IMethods IIThe EndJan 14, 2019JavaScript Miscellany2Properties of functionsFunctions are objects, and have propertieslength – the number of formal parametersarguments – the Arguments object, which is “like” an array of actual parametersNote: length is not necessarily equal to arguments.lengthcaller – the function that invoked this one, or null if the function was invoked from the top levelprototype (for constructor functions) – an object that defines properties and methods of functions created with this constructor3The for...in loopThis kind of loop has the syntax for (variable in object) statementEach property of the object (or, if an array, each index of the array) is assigned in turn to variableProperties will be assigned in an arbitrary orderIt turns out, however, that the for...in loop does not loop through all properties of an objectBuilt-in methods, and many built-in properties, are flagged as nonenumerableAll built-in properties of functions are nonenumerableThere are lots of little surprises like this in JavaScript 4Global and local variablesA variable is local to a function ifIt is a formal parameter of the functionIt is declared with var inside the function (e.g. var x = 5)Otherwise, variables are globalSpecifically, a variable is global ifIt is declared outside any function (with or without var)It is declared by assignment inside a function (e.g. x = 5)5Methods IFirst we construct an object:function Point(xcoord, ycoord) { this.x = xcoord; // keyword "this" is mandatory this.y = ycoord;}myPoint = new Point(3, 5);A method is a function that is associated with, and invoked through, an object (hence can use this)Here is a “function” that makes no sense by itself:function distance(x2, y2) { function sqr(x) { return x * x; } return Math.sqrt(sqr(this.x – x2) + sqr(this.y – y2));}6Methods IIWe can turn this function into a method, like so:myPoint.dist = distance;Now this inside the function refers to myPoint, and we can say:document.write("The distance is " + myPoint.dist(6, 9));If we don’t want to permanently associate the function with myPoint, but just use it briefly, we can say:document.write("The distance is " + dist.call(myPoint, 6, 9));Or:document.write("The distance is " + dist.apply(myPoint, [6, 9]));The difference between these two Function methods is:call takes an object and an arbitrary number of actual parametersapply takes an object and an array of actual parameters7The
View Full Document