1. Six Data Types
5 basic types: Undefined, Null, Boolean, Number, String (among them Undefined derives from Null)
1 complex type: Object (essentially an unordered set of key-value pairs)
2. String to Number Conversion
-
Number(str): Evaluates first then converts (first valueOf then toString, if neither works it's NaN), generally not what we expect, for example Number('')=Number(false)=Number(null)=0 while var x;Number(x)=NaN... So generally we use the following two methods
-
parseInt(str): Can specify radix, recommend using parseInt(x, 10); format, i.e., always specify radix
-
parseFloat(str): Cannot specify radix, returns integer when parsing integers, not floating point
3. Getting String Length
String type values all have length property. str.length returns integer string length value, not through other functions to get string length
4. Pass by Value vs Pass by Reference
Function parameter passing is all pass by value
5. Scope Chain
Essentially a stack, stores variable objects of each layer (similar to compiler's symbol table pointer stack), variable object holds access permissions for all variables and functions in that layer, if that layer is a function, then variable object is arguments object, stack top is variable object corresponding to currently executing context environment, stack bottom is variable object corresponding to global execution environment.
6. Scope
No block-level scope, has function-level scope
7. Two Methods to Create Object Objects
- var obj = new Object();obj.attr = value;
Traditional way, call constructor function to create object
- var obj = {attr1 : value1, attr2 : value2} or var obj = {"attr1" : value1, "attr2" : value2}
Object literal notation, property names can be strings
Note:
-
Unless property name has ambiguity such as: null, var etc., generally don't use strings as property names, of course just habit constraint
-
When defining object with object literal method, does not call its constructor
8. Two Methods to Access Property Values
-
obj.attr
-
obj["attr"] Advantage is can access properties through variables, such as var attrName = "attr";obj[attrName] more flexible
9. Array Declaration and Initialization
-
var arr = new Array(value1, value2...);
-
var arr = Array(...); can omit new
-
Array literal: var arr = [value1, value2...];
Note: When defining array with array literal does not call its constructor either
10. Array Related Functions
See Appendix
11. Difference Between Function Declaration and Function Expression
-
function fun(){...} JS engine generates this function object when loading source code
-
var fun = function(){...} JS engine generates this function object only when executing
12. Function Overloading
Does not support overloading. Later declared function will cover earlier declared one, essentially multiple assignment operations on function name (function name is just a pointer variable)
13. Special Properties Inside Functions
-
arguments.callee Function pointer, points to function owning this arguments object, i.e., current function
-
this Reference to current execution environment, top-level this is window
-
arguments.callee.caller Function pointer, points to function calling current function, returns null if none
Note: this can be object reference or function reference, but callee and caller can only be function references
14. Function Object Properties and Methods
-
length Number of named parameters function expects, in JS can pass arbitrary number of parameters to function, because besides formal parameters, can also use arguments to get any parameter
-
prototype Points to function's prototype object
-
call(context, arg1, arg2...) Used to call function in specific scope, decouples tight coupling between object and function
-
apply(context, arguments or other array object) Same function as above, supports array parameters
-
bind/unbind(context, arg1, arg2...) Bind/unbind execution environment or parameters, can generate new functions from existing functions, but consecutive binding with bind is ineffective (consecutive != multiple), for example:
function fun(){ alert(this.data); } var obj = { data : 'obj_data' }; var newObj = { data : 'new_obj_data' }; fun1 = fun.bind(obj); fun1(); fun2 = fun1.bind(newObj);//consecutive binding fun2(); fun3 = fun.bind(newObj);//multiple binding fun3();
Above code outputs 'obj_data', 'obj_data', 'new_obj_data', second binding failed, because bind function is implemented using call internally, effect of consecutive binding is similar to:
//function from first binding
fun1 = fun.call(obj);
//function from second binding
fun2 = fun1.call(newObj);
In function from second binding, this inside fun1 indeed points to newObj, but fun1 doesn't use this at all, so no impact
15. Some Common Sense
-
this always points to object it belongs to (whose property you are, that's who this inside you points to)
var obj1 = { data : 1, fun : function(){ alert(this.data); } }; var obj2 = { data : 2 }; obj1.fun(); obj2.fun = obj1.fun; obj2.fun();Above code outputs 1 and 2, because after executing second to last sentence, obj2 adds new fun property, value is reference to obj1.fun, but because obj2.fun is obj2's property, so this points to obj2
-
Define member functions on constructor prototype as much as possible, because functions defined directly in constructor have runtime closure overhead
-
Should use single quotes in JS, because only double quotes in JSON and XML, using single quotes can avoid escaping
-
Initialize at same time as variable declaration as much as possible, to distinguish undefined means undeclared. Because typeof operator returns "undefined" for both declared but uninitialized variables and undeclared variables
-
NaN (Not a Number) is not equal to any value, including NaN itself, so need to use isNaN() function to judge
-
Can only dynamically add properties to reference type values. Adding properties to primitive type values won't error but has no meaning
-
Arrays automatically grow according to index. Need to note length property is writable, meaning can dynamically set array length, such as truncating tail elements
-
Function name is just a pointer variable. function fun{...} fun = null; just breaks reference relationship, function body is not destroyed
Appendix
1. Basic Data Types
-
Undefined Default value of defined but uninitialized objects
-
Null Represents an empty object pointer, so typeof detection returns object
-
Boolean Boolean value, note Boolean() conversion function, rules as follows:
-
true/false ~ unchanged
-
Non-empty string/empty string ~ true/false
-
Non-zero number/0 and NaN ~ true/false
-
Any object/null ~ true/false
-
undefined ~ false
Above rules are very important, because if conditions automatically apply Boolean() conversion, and if(obj) is very common in JS code, many times flow control errors are caused by if condition automatic conversion
-
Number Numeric value, +0 and -0 are equal in JS, note NaN, it's not equal to anything, including itself, and it's neither greater than n nor less than or equal to n. Number variable supports toString() function, can be used for radix conversion of numeric strings, for example var num = 17;num.toString(16) returns "11"
-
String String, note string immutability, should use array + join instead of loop + for massive concatenation operations
2. Object Type Variable Properties and Methods
-
Constructor Stores reference to constructor function
-
hasOwnProperty(propertyName) Used to check if current object owns specified property (here "property" includes attributes and methods)
-
isPrototypeOf(obj) Used to check if current object is prototype of specified object
-
propertyIsEnumerable(propertyName) Used to detect if specified property is enumerable
-
toLocaleString() Equivalent to toString() function, but adds locale characteristics
-
toString() Returns string representation of object
-
valueOf() Returns string, numeric or boolean representation of object
3. Common Reference Types
-
Function Functions are also objects in JS, very flexible, for example:
var load = window.onload; window.onload = function(){ //do something load();//so simple, add a pair of parentheses to execute immediately } -
Array Array type has most operation functions
-
Stack functions: push() insert one item at array end, pop() pop last item
-
Queue functions: push() same as above, shift() dequeue first item and return first item; reverse queue (enqueue at front, dequeue at back) unshift()/pop()
-
Sort functions: sort(fun) no parameter compares strings ascending order, with parameter pass custom comparison function returning positive/negative/0; reverse() reverses order
Note: sort()/reverse() both directly change original array, and sort() default implementation is not very scientific, sorting result for [1, 3, 10, 5] is [1, 10, 3, 5], to get desired result, must pass custom comparison function
4. Operation functions:
1. arr.concat(arr1, arr2...) connect to form new array
2. arr.slice() equivalent to substring string截取 effect, usage is also same
3. arr.splice() insert items into array middle, splice(startIndex, num, item1, item2...) means replace num items starting from startIndex with various items, only first two parameters means replace num items starting from startIndex with empty (i.e., delete), can use splice to implement delete/replace/insert operations.
*Note*: splice function also directly changes original array.
5. Position functions: indexOf(value) and lastIndexOf(value), find index position of value, return -1 if not found, internally uses strict equality operator (===)
6. Iteration functions: every(), filter(), forEach(), map(), some() all run specified method on each array item, IE9+ supports and not commonly used, won't elaborate here
7. Reduction functions: reduce(), reduceRight() not introduced, reason same as above
3. Date type: Related content is quite extensive, see W3School
- RegExp type: var regex = /^cat$/i; create regular expression (RegExp type), supported patterns are g, i, m representing global mode, ignore case mode, multiline mode. Of course, can also use new RegExp(strRegex, strMode), but what reason to use this method?
JS supports regex capture, var matches = regex.exec(text); get captured content through matches[0], matches[1]...
Normal regex matching: regex.test(text) returns true/false
-
Primitive wrapper types: Boolean, String and Number, always meeting but didn't notice, for example:
var str = 'smilestome'; var str_ = str.substring(1);
Above code is equivalent to:
var s1 = new String('smilestome');//create wrapper type instance
var s2 = s1.substring(1);//call corresponding method on instance
s1 = null;//destroy instance
Automatic boxing and unboxing, to make primitive data types easier to use, but need to note: new String() and String() conversion methods are different, former returns object type, latter returns string type, given such difference, mixing causes unnecessary trouble, so we have no reason to explicitly create wrapper types. Boolean, Number are similar.
No comments yet. Be the first to share your thoughts.