This post records some of the questions I met in technical interviews. Some of them are tricky.
Functional programming is one of the programming paradigms. Here are some features:
Advantages:
Closure is those functions what can visit independent (free) variables. In other words: closures can memorizes the environment when they were created.
function init() {
var name = "test";
function display() {
console.log(name);
}
}
The inside function can visit variables declared in its outside scope.
function func() {
var name = "test";
return function() {
console.log(name);
}
}
var f = func();
f();
A closure is a special object that made of a “function” and the scope where the function was created.
Some usage:
var createClass = function() {
var ct = 0;
function changeBy(n) {
ct += n;
}
return {
add1: function() {
changeBy(1);
},
value: function() {
return ct;
}
}
}
Disadvantages:
Negative effects on performance and memory.
Reference: MDN
Read: MDN
function A() {
this.p1 = 0;
}
A.prototype.p2 = 0;
var a = new A();
var b = new A();
console.log(a.p1); // 0
console.log(b.p1); // 0
a.p1 = 2;
console.log(a.p1); // 2
console.log(b.p1); // 0
A.prototype.p2 = 2;
console.log(a.p2); // 2
console.log(b.p2); // 2
Declare methods in construction takes no advantages of closure, so it should be replace by prototype.
http://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype
Reference: React docs