Javascript Programming
Javascript Programming
Mendel Rosenblum
...
● In non-method functions:
○ this will be the global object
○ Or if "use strict"; this will be undefined
CS142 Lecture Notes - JavaScript Programming 4
functions are objects - can have properties
function plus1(value) {
if (plus1.invocations == undefined) {
plus1.invocations = 0;
}
plus1.invocations++;
return value + 1;
}
● bind() method - creates a new function with this and arguments bound
○ let newFunc = func.bind({z: 2}, 3);
○ newFunc() prints '{ z: 2 } 3'
● On an object property read access JavaScript will search the up the prototype
chain until the property is found
● Effectively the properties of an object are its own property in addition to all the properties up
the prototype chain. This is called prototype-based inheritance.
● Property updates are different: always create property in object if not found
● Prototype-based inheritance
○ Single inheritance support
○ Can be dynamically created and modified
Browser:
function callbackFunc() { console.log("timeout"); }
setTimeout(callbackFunc, 3*1000);
Server:
function callbackFunc(err, data) { console.log(String(data)); }
fs.readFile('/etc/passwd', callbackFunc);
let globalVar = 1;
function localFunc(argVar) {
let localVar = 0;
function embedFunc() {return ++localVar + argVar + globalVar;}
return embedFunc;
}
let myFunc = localFunc(10); // What happens if a call myFunc()? Again?
● myFunc closure contains argVar, localVar and globalVar
Global
return (function () {
var i = 1; var i = 1;
. . . . . .
Versus
function f() { function f() {
i++; i++;
return i; return i;
} }
return f; No globals
})();
let s = JSON.stringify(obj) =
'{"ps":"str","pn":1,"pa":[1,"two",3,4],"po":{"sop":1}}'
typeof s == 'string'
JSON.parse(s) // returns object with same properties
● JSON is the standard format for sending data to and from a browser