Javascript Study Notes

function

Function declaration statements

1
2
3
function funcname({arguments}) {
// return some statements
}

Function definition expressions

1
2
3
var funcname = function({arguments}) {
// return some statements
}

Function declaration statements may only appear at the top level of the funtion they are nested within.That is, function definitions may not appear within if statements, while loop, or any other statements.
The function declaration statement also declares the function name as a variable and assigns the function object to it. Like variables declared with var, functions defined with function definition statements are implicitly “hoisted” to the top of the containing script or function, so that they are visible throughout the script or function. With var, only the variable declaration is hoisted—the variable initialization code remains where you
placed it.
Both the function name and the function body are hoisted: all functions in a script or all nested functions in a function are declared before any other code is run. This means that you can invoke a Javascript function before you declare it.
Like the var statement, function declaration statements create variables that cannot be deleted. These variables are not read-only, however, and their value can be overwritten

prototype

deepclone

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Object.prototype.deepClone = function(top) {
var Obj = [];
if(!top)
top = this;
for(var key in this) {
if(top === this[key]) {
return;
}
Obj[key] = typeof this[key] === 'object'
? Obj[key] = this[key].deepClone(top)
: Obj[key] = this[key];
}
return Obj;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Object.prototype.deepClone = function(top) {
var Obj = [];
if(!top) {
top = this;
}
for(var key in this) {
if(top === this[key]) {
return;
}
if(typeof this[key] === 'object' ){
Obj[key] = this[key].deepClone(top)
} else if(typeof this[key] === 'function' &&
this[key] !== Object.prototype.deepClone){
// will find the deepClone function in the prototype.Object
var func = function () {};
func.prototype = this[key].deepClone(top);
Obj[key] = new this[key];
Obj[key].prototype = new func;
} else {
Obj[key] = this[key];
}
}
return Obj;
}

bind

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}

var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(
this instanceof fNOP && oThis ? this : oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};

fNOP.prototype = fToBind.prototype;
fBound.prototype = new fNOP();
return fBound;
};