- The "keys" of an array are the indices!
var myarray = [ "potatoes" "tomatoes" "celery" ]; var sample = []; for (var x in myarray) { sample.push(x); } // sample = [ 0 1 2 ] NOT [ "potatoes" "tomatoes" "celery" ]
- Primitives are passed by value and the references of Objects are passed by value.
thisin a method refers to the object from which the method was invoked. See JavaScript “this” keyword.
var m = function() { this.value = this.value +1; } var a = { "value":1, "m":m }; var b = { "value":100, "a":a }; a.m(); // a.value = 2 b.a.m(); // a.value = 3, b.value = 100 b.a.m.call(b); // b.value = 101
- Objects in Javascript are associative arrays. To create an object is to create an associative array. One way of doing this is through the use of functions.
function f() { var x = 1; this.y = 100; this.addup = function addup(v) { this.y = this.y + v; }; return this; } var func1 = f(); var func2 = f(); func1.addup(1); [ func1.y, func2.y ]; // [ 101, 101 ] func2 = new f(); func2.addup(5); [ func1.y, func2.y ]; // [ 101, 105 ] [ func1.x, func2.y ]; // [ NaN, undefined ]
The last line is strange (Mozilla). I personally think it's a bug. I was expectingundefined. See Which way is best for creating an object in javascript? is “var” necessary before variable of object?.
undefinedis not a keyword in Javascript. It is just another variable that generally is undefined. The safest way to test if variablexis undefined istypeof(x) == "undefined". Note
var a = "welcome"; var b = { "a":"apple", "k":"kite", "z":"zebra" }; b["b"] == null; // TRUE b["b"] == undefined; // TRUE b["b"] === null; // FALSE b["b"] === undefined; // TRUE
However starting in Javascript 1.8.5,undefinedis a global non-writable variable whose type isundefined. So
var undefined = "trickster"; // doesn't do anything undefined === undefined; // TRUE typeof(undefined) == "undefined"; // TRUE
Tuesday, November 13, 2012
Javascript Note 1
Things I learned while writing a Thai transcription script in Javascript.
Subscribe to:
Post Comments (Atom)
C has = (assignment operator), == (equivalence operator) but no ===!
ReplyDeleteYes, that's right. === means "same object as". In C, you can test for "same object as" (using the word "object" loosely here) by comparing memory address. If two objects have the same memory address, then they are the same. But because there is no reliable way to get the memory address of objects in Javascript, they had to create the === operator. On a related note, in Java, Object.equals() is used for equivalence and == is used for "same object as".
ReplyDelete