Sunday, October 23, 2011

video reaction

The first thing i learn from the video is scope.
I never know I can do this in js
function assure_positive(matrix, n){
   for (var i = 0; i<n; i +=1){
      var row = matrix[i];
      for (var i = 0; i< row.length; i +=1){
          if(row[i] <0){
              throw new error('')
 }}}}
the way I usually did is define the variable with a new name

then, another thing surprises me is function in js can be called by too many or few argument, this usually makes a error in other language

I think the closure is a tricky point
Douglas shows a example in three ways:
1st:
var name = ["one", "two", "three"];
var digit_name=function (n){
 return name[n];
}
alert(digit_name(2));
this can works, but it will reduce the performance of the function if we just need the "name" variable in the only function digit_name

2nd:
var digit_name = function(n){
  var name = ["one", "two", "three"];
  return name;
};

alert(digit_name(2));
this also works, but it will take more time to process because we need declare the array every single time we call the function

var digit_name = (function (){
  var names = ['one', 'two', 'three'];
  return function (n){
    return name[n];
  };
}());
this is the best way that can avoid two problem happens before, and it is also js' feature.

No comments:

Post a Comment