Skip to content

Instantly share code, notes, and snippets.

View tfanme's full-sized avatar
🎯
Focusing

tfan tfanme

🎯
Focusing
View GitHub Profile
@tfanme
tfanme / valueTypeAndReferenceType.js
Created October 10, 2013 08:17
JavaScript: value type and reference type
var str = 'abcde';
var obj = new String(str);
function newToString() {
return 'hello, world!';
}
function func(val) {
val.toString = newToString;
}
@tfanme
tfanme / explicitDeclaration.js
Created October 10, 2013 08:23
JavaScript: 显式声明
// 声明变量 str 和 num
var str = 'test';
var num = 3 + 2 - 5;
// 声明变量 n
for (var n in Object) {
// ...
}
// 声明变量 i, j, k
@tfanme
tfanme / copyingObjects.js
Created October 19, 2013 13:21
Copying Objects
// Shallow copy(浅拷贝)
var newObject = $.extend({}, oldObject);
// Deep copy(深拷贝)
var newObject = $.extend(true, {}, oldObject);
@tfanme
tfanme / copyingArrays.js
Created October 19, 2013 13:22
Copying Arrays
var array1 = [0, 1, 2];
var array2 = array1.slice(0); // copy
@tfanme
tfanme / de-reference.js
Created October 19, 2013 13:24
If you de-reference an object you can no longer alter its value
function foo(bar) {
bar = { x: 2 };
}
var a = { x: 1, y: 7 };
foo(a);
alert(a.x); // still 1
@tfanme
tfanme / passByReference.js
Created October 19, 2013 13:27
Reference types are passed by reference
function foo(bar) {
bar.x = 2;
}
var a = { x: 1, y: 7 };
foo(a);
alert(a.x); // => 2
var a = { x: 1, y: 7 };
var b = a;
b.x = 2;
@tfanme
tfanme / comparedByReference.js
Created October 19, 2013 13:28
Reference types are compared by reference
var a = { x: 1, y: 7 };
var b = { x: 1, y: 7 };
if (a == b) // => false
if (a === b) // => false
b = a;
if (a == b) // => true
if (a === b) // => true
@tfanme
tfanme / mutable.js
Created October 19, 2013 13:29
Reference types are mutable
var point = { x: 1, y: 7 };
point.x = 2;
point.y = 9;
function fn() {
return true;
};
fn.x = 1;
@tfanme
tfanme / passedByValue.js
Created October 19, 2013 13:31
Primitive types are passed by value
// sample 1
function foo(bar) {
bar = 2;
}
var a = 1;
foo(a);
alert(a); // => 1
// sample 2
var a = 1;
@tfanme
tfanme / comparedByValue.js
Created October 19, 2013 13:32
Primitive types are compared by value
var a = "Roger";
var b = "Roger";
if (a == b) // => true
if (a === b) // => true