Something Basal About Function

Closure

1
2
3
4
5
6
7
8
9
10
11
12
13
function createFunctions() {
  var ans = [];

  for (var i = 0; i < 7; i++) {
    ans[i] = function() {
      return 4*i;
    };
  }
  return ans;
}
createFunctions().map(function (item) {
  console.log(item());
});

print:

1
2
3
4
5
6
7
28
28
28
28
28
28
28

call(), apply(), bind()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var table = {
  entry: [{key: 1, value: 4}, {key: 'r', value: 't'}],
  addEntry: function(key, value) {
    this.entry.push({
      key: key,
      vlaue: value
    });
  },
  forEach: function(f, thisArg) {
    var entry = this.entry;

    for (var i = 0; i < entry.length; i++) {
      var ent = entry[i];
      f.call(thisArg, ent.key, ent.value);
    }
  }
};

var table2 = {entry: []};
table.forEach(table.addEntry, table2);

console.log(table2);

copy table.entry to table2

object arguments

1
2
3
4
5
6
7
function sum(a, b) {
  return a+b;
}

function sumApply(a, b) {
  return sum.apply(this, arguments);
}

Comments