JavaScript

Contents
      1. JavaScript Pitfalls
        1. Global Vars
        2. this
        3. with
        4. Prototype extension
        5. Other
              1. Type Coercion
              2. slice() vs. splice()
      2. Links

JavaScript Pitfalls


Global Vars

 function tenfold(num) {
     n = num * 10;
     return n;
 }
 n = 10;
 much = tenfold(n);
 n = n + much;

this

 value=10;
 obj = {
	value: 1,
	foo: function() { return bar()+this.value; },
	bar: function() { return 2*this.value; }	
 };
 say(obj.foo());  // 21

with

with does not create undefined members:
 var obj = {foo: 42};
 with(obj) {
     foo = 010;  // OK, foo==8 (octal, another pitfall)
     bar = 23; // sets global var, not obj.bar
 }
cf. with Statement Considered Harmful

Prototype extension

	var map = {first: "foo", last: "bar"};
	Object.prototype.junk = "hello";
	for each(item in map) {
		i++;
	}
i is incremented by at least 3.

Other

Type Coercion
slice() vs. splice()
 arr = [1,2,3,4,5,6]
arr.slice(1,2) returns [2], e. g. returns new array with items from start index 1 to excluding the end index 2. arr.splice(4,2) sets arr to [5,6], e. g. reduces arr to the 2 items starting at index 4.

Links


EditContents