My notes while watching...
History of JavaScript with Doug Crockford JavaScript architect
delete statment.
Arrays
How to decide if a value is an array or object? Two ways
Functions are first class objects.
function statement is shorthand for function assigned to a new var. e.g.
function foo{} is the same is var foo = function foo() {};
function names don't exist in a separate namespace.
can be defined inside of other functions.
inner function has access to the variables and parms of functions it's contained within (Static Scoping or Lexical Scoping) - got this right
function invocation
eval is the most misused feature of the language. don't use it. takes a string and compiles it. wastes time. reason they use it: don't know how to do subscript notation; . can use it with JSON - only when you can trust your server. use parseJSON method instead of eval. (The browser uses eval which is why it's there.)
Function function takes a string and compiles it - shouldn't be used in the same way eval shouldn't be used.
avoid new Boolean, new String, new Number because it's a vestigial remnant from Java. Particularly confusing with booleans - a new boolean is true.
3 - 19:45.
Make another object based on another object:
function object(o){
function F() {}
F.prototype = o;
return new F();
}
The global object is always there, but you can't name it or get to it. In browsers, window is the global object. (Browsers create a new object "window" and assign global to it.) Contains all global variables and prototypes.
Global variables are evil
Recommendation: use an anonymous function to wrap your application. take advantage of function scope to encapsulate state. Like this:
JAVAJOSH.WeBrowser = function() {
// define common vars
// define common funcs
return {
getNextPoser: function(cat, diff) {
},
showPoser: function () {
// I guess this is the entry point
}
};
}
} (); // the parens actually invoke this function
This is a "powerful platform on which to make our applications much more reliable".
Video 4
Type system -
Style
Recommend: always use full forms including semi-colons. Why? Because when compiler sees an error it attempts to replace a nearby linefeed with a semicolon and try again, which can mask errors. Intentional error to make it easier for beginners.
Recommend: break line only after punctuation; don't break after name, string number, ) ] ++ --. Will help detect errors and avoid copy paste errors.
Recommend: avoid tricky expressions with comma operator ?. Avoid extra commas in array literals. It's bad because netscape and IE will report different lengths.
Always use blocks (e.g. in if statments). Only use blocks with structured statments. Define all variables at the top of the function (no advantage to defining at place of first use).
avoid falltrough switch
don't use assignment in condition of if and while. more likely you meant if (a == b)
be aware that == does type coercion. avoid if (a == null) but use if (!a) or if (a === null) [where else does this have an impact?]
never used javascript: as a label, or javascript in urls.
History of JavaScript with Doug Crockford JavaScript architect
- Eich wanted to do Scheme; told no by Netscape
- Netscape and Sun alliance - but Sun wanted Java to be in the browser
- ECMA language
- load and go delivery - delivered as source (not binaries).
- loose typing - benefit in expressiveness, easier to write.
- objects are general containers (objects are hashtables - "brilliant")
- prototypal inheritance (objects inherit from objects without classes)
- lambda
- Linkage through global variables - a really bad idea (security, reliability issues)
- number -
- internally 64 bit floating iee-754 "double"; only approximation (do arithmetic in whole numbers to avoid problems).
- NaN is a special number that's "toxic"; NaN != NaN. typeof NaN is number!
- Number() function produces NaN if has a problem; similar to + prefix operator
- parseInt(value, radix) - first digit 0 makes it think it's octal, so always include radix.
- Math object a mistake, but has useful functions on it.
- string -
- sequence of 0 or more 16 bit characters
- Encoded in UCS-2 not UTF-8. (no awareness of surrogate pairs)
- immutable - must make new strings
- no separate character time.
- can test with == (yay!)
- single and double quotes ' or "
- has a .length property - not the same as unicode character
- defines lots of useful methods
- booleans
- true and false
- Boolean function
- false: false, null, NaN, 0, "" [empty string]
- string 0 is true, string
- null
- undefined
- default value of parms and values
- confusing if a variable has
- extract a member that doesn't exist.
- new Object() produces empty container of name value pairs.
- can access with dot or bracket
- no visible hash nature (JScript implemented with linked lists)
- Not untyped - it's just loose.
- Syntacticly C, but it allows functions to be values.
- start with a letter or _ or $
- convention, vars, parms, members, functions start with lower case by convention
- initial underscore
- recommended to avoid $ for machine; _ for
- huge reserved words; also apply to member names
- // /**/ for comments
- + used for addition and concat (a mistake because loosely typed languages shouldn't have operator overloads
- == and != can do type conversion --- recommend that you do === and !== instead to avoid coercion; will run faster and more reliable. (Microsoft caused the reversal of this convention)
- && works oddly - if first operand is truthy, result is second operand else result is first operand. Common idiom for nullity check: return a && a.member;
- || can be used to set a default value - var foo = input || my_default;
- ! does what you expect
- !! produces a boolean :)
- bitwise & | >> <<- take floating point, turn into 32 bit integer, then turn it back into fp. Note that shifting in Javascript is slower than multiplying by 2.
- labeled breaks for loops
- for statemant
- special version for objects - for (var name in object){if object.hasOwnProperty(name){} //do something}. otherwise will go through all parent's keys as well.
- switch statment; switch value can be a number or a string; case values can be expressions. switch (express){case ';':case',";punctuation(); break;default:somethingElse();}
- exceptions: throw new Error(reason); or throw { name: exceptionName, message: reason} (that's an object literal)
- try/catch - only ever one catch clause, switch on name. Some built in exception names.
- with statement - ambiguous with global variables, don't use it. (5.20 into video 2)
- function name(parms){statments;}
- var name; var stuff = 0; if no initialization value, undefined.
- blocks don't have scope! different from C languages! only function scope! variable in a function visible everywhere in function. declaring a variable twice only makes it get created once.
- return. return expression; or return; if no expression, return value is undefined, except for constructors that return "this".
- Unordered collection of name/value pairs
- names are strings
- values can be any time incl other objects
- good for records and trees
- like a little database.
- object literal notation -
- can be used anywhere a value might appear
- : seperate name value, , seperates pairs. Note, don't leave trailing comma.
- names can be names or strings (optional quotes)
- myObject.name is the same as myObject['name']; (not quite the same 'cause you can have a reserved word in the second form!!! Ugh!)
- make a new empty object with var myObj = {};
- factory methods (makers) common idiom.
- tip: can use object parameters for "named parameters" including suitable defaults - think about replacing long list of parms with an object
- augmentation - can add new members by assignment.
- Linkage- objects can be created with a "secret link" to other objects - member search will fall back to the secret link. object(o) functions makes a new empty object with a link to object o. not used for storing - new members only add to primary member.
- var myNewObject(myOldObject); creates a "subclass". Note that assignment or "overriding" doesn't change the parent object - you create a copy of the member in the child class with a different value.
- simple: any object can inherit from older objects
- Prototypal inheritance
- js functions take the place of classes, methods, constructors, and modules!
- greater expressive power.
- sometimes deleting things makes them mutate (lets the parent object "shine through")
- only single inheritance
- all objects linked back to Object.prototype. but doesn't have any useful methods. no equals (contains the same stuff), or copy. but does have "hasOwnProperty".
- mark and sweep garbage collection
- new Object()
- {} <-- preferred. (smallest most expressive)
- object(Object.prototype)
delete statment.
Arrays
- Unusual because they inherit from Object
- indexes converted to strings and used as names for retrieving values
- efficient for sparse arrays (e.g. 1% population)
- not efficient for other cases
- good thing: no need to provide length or type on creation :)
- have length member - one higher than highest integer subscript (allows traditional for loop)
- literals [] myList =['ad','sdf','sf']; can append to it.
- dot notation cannot be used. use [] not new Array() to create a new array.
- inherits the array methods: concat, join, push, pop, slice, sort, splice
- delete array[number] removed item but leaves a hole. to remove hole use splice
- myArray = ['a','b','c','d']; delete myArray[1]; myArray.splice(1,1)
- linked to Array.prototype
How to decide if a value is an array or object? Two ways
- value.constructor === Array
- value instanceof Array
- niether work if value came from another frame. (omission in the language)
Functions are first class objects.
- functions can be passed, returned stored as a value
- functions can inherit from Object (it can have methods!)
function statement is shorthand for function assigned to a new var. e.g.
function foo{} is the same is var foo = function foo() {};
function names don't exist in a separate namespace.
can be defined inside of other functions.
inner function has access to the variables and parms of functions it's contained within (Static Scoping or Lexical Scoping) - got this right
- scope continues after the parent function returns.
- multiple calls to same function won't interact because local variables are renewed (see fade() example 3 - 5:30)
- first lambda language to go mainstream.
function invocation
- called with too many objects, ignored
- too few objects, missing vals are undefined
- no type checking
- method form: myObject.methodName(args);
- get an extra parm called "this" set to myObject
- allows us to reuse functions on different objects - relies on invocation to know what object it's linked to.
- function form: functionObject(args)
- this is set to the global object -
- not useful because helper functions don't get to access the outer "this".
- Constructor form: new functionObject(args)
- new object created and assigned to "this"
- this will be returned if no explicit return value.
- functions get a special parm called "arguments" when invoked
- an array-like object (no array methods) containing all arguments
- has a length member
- good for functions that take variable number of parameters
- Object
- Array
- Function
- Number
- String
- Boolean
eval is the most misused feature of the language. don't use it. takes a string and compiles it. wastes time. reason they use it: don't know how to do subscript notation; . can use it with JSON - only when you can trust your server. use parseJSON method instead of eval. (The browser uses eval which is why it's there.)
Function function takes a string and compiles it - shouldn't be used in the same way eval shouldn't be used.
avoid new Boolean, new String, new Number because it's a vestigial remnant from Java. Particularly confusing with booleans - a new boolean is true.
3 - 19:45.
Make another object based on another object:
function object(o){
function F() {}
F.prototype = o;
return new F();
}
The global object is always there, but you can't name it or get to it. In browsers, window is the global object. (Browsers create a new object "window" and assign global to it.) Contains all global variables and prototypes.
Global variables are evil
- functions in an app can clobber
- cooperating apps clobber
- minimize it - mashups are going to fail.
- made much worse by the implied global - any var not declared is assumed to be global.
- jslint.com helps identify that sort of stuff. (doug wrote it)
Recommendation: use an anonymous function to wrap your application. take advantage of function scope to encapsulate state. Like this:
JAVAJOSH.WeBrowser = function() {
// define common vars
// define common funcs
return {
getNextPoser: function(cat, diff) {
},
showPoser: function () {
// I guess this is the entry point
}
};
}
} (); // the parens actually invoke this function
This is a "powerful platform on which to make our applications much more reliable".
Video 4
Type system -
Style
- style isn't about personal taste
- it's about rigor in expression
- clearness in presentation
- product adaptability & longevity
- good rules keep quality high
- critically important for JavaScript
- the language is considered by some to be too soft - requires discipline for balance.
- most JavaScript is crap
Recommend: always use full forms including semi-colons. Why? Because when compiler sees an error it attempts to replace a nearby linefeed with a semicolon and try again, which can mask errors. Intentional error to make it easier for beginners.
Recommend: break line only after punctuation; don't break after name, string number, ) ] ++ --. Will help detect errors and avoid copy paste errors.
Recommend: avoid tricky expressions with comma operator ?. Avoid extra commas in array literals. It's bad because netscape and IE will report different lengths.
Always use blocks (e.g. in if statments). Only use blocks with structured statments. Define all variables at the top of the function (no advantage to defining at place of first use).
avoid falltrough switch
don't use assignment in condition of if and while. more likely you meant if (a == b)
be aware that == does type coercion. avoid if (a == null) but use if (!a) or if (a === null) [where else does this have an impact?]
never used javascript: as a label, or javascript in urls.
No comments:
Post a Comment