728x90


1. for문 안의 배열 iterate
 
 Example:
 var myArray = [ “a”, “b”, “c” ];
 var totalElements = myArray.length;
 for (var i = 0; i < totalElements; i++) {
 console.log(myArray[i]);
 }


 Solution: always use regular for loops to iterate arrays.
 var myArray = [ “a”, “b”, “c” ];
 for (var i=0; i<myArray.length; i++) {
  console.log(myArray[i]);
 }
 
 << myArray 에 대한 간섭으로 인해 잘못된 정보를 참조할 수 있다고 하는 내용인데요...
    이글에 대한 많은 분들이 댓글 이슈를 달아주시기도 한 내용입니다.
 그럼 이슈가 무엇이였냐면요... 위 Example 에 대한 예시가 잘못되었다는 것이죠
 Example :
  for (var el in myArray){}
 Solution :
  for(var i = 0, iMax = myArray.length; i < iMax; i++){}
 이런 식으로 했어야 하였다는 이슈가 있더군요.
 
2. 배열 정의
 Example:
 var myArray = new Array(10);
 Solution: Use literal notation to initialize arrays. Do not predefine array length.
 var myArray = [];
 
 << 문제점 2개를 이야기 하는데요
      var a = new Array(10); // 빈 item 에 접근으로 인해 undefined 발생
  var a = {"","","","",....,""}; // 속도가 느린문제
  이런 문제를 앉고 있다고 하네요 >>
 
 
3. Undefined properties
 Example:
 var myObject = {
  someProperty: “value”,
  someOtherProperty: undefined
 }
 Solution: if you want to explicitly declare a uninitialized properties inside an object, mark them as null
 var myObject = {
  someProperty: “value”,
  someOtherProperty: null
 }
 
 << object 에 없는 값과 있으나 undefined 로 정의한 값을 구분할 수 없다는 이슈였습니다.
 typeof myObject['someOtherProperty'] // undefined
 typeof myObject['unknownProperty'] // undefined   >>
 


4. 클로저 오용
 Example:
 function(a, b, c) {
  var d = 10;
  var element = document.getElementById(‘myID’);
  element.onclick = (function(a, b, c, d) {
   return function() {
    alert (a + b + c + d);
   }
  })(a, b, c, d);
 }
 Solution: use closures to simplify your code
 function (a, b, c) {
  var d = 10;
  var element = document.getElementById(‘myID’);
  element.onclick = function() {
   //a, b, and c come from the outer function arguments.
   //d come from the outer function variable declarations.
   //and all of them are in my closure
   alert (a + b + c + d);
  };
 }
 
 << 변수에 대한 접근 범위를 몰라 중복해서 불필요한 파라미터를 정의하는 것을 말합니다. >>
 
5. loop 안의 클로져
 Example:
 var elements = document.getElementByTagName(‘div’);
 for (var i = 0; i<elements.length; i++) {
  elements[i].onclick = function() {
   alert(“Div number “ + i);
  }
 }
 Solution: use a second function to pass the correct value.
 var elements = document.getElementsByTagName(‘div’);
 for (var i = 0; i<elements.length; i++) {
  elements[i].onclick = (function(idx) { //Outer function
   return function() { //Inner function
    alert(“Div number “ + idx);
   }
  })(i);
 }


 << 내부 클로져의 경우 최종값 i 값을 참조한다는 문제였습니다. >>
 
6. DOM 으로인한 메모리 누수
 Example:
 function attachEvents() {
  var element = document.getElementById(‘myID’);
  element.onclick = function() {
   alert(“Element clicked”);
  }
 };
 attachEvents();
 Solution: avoid those closures or undo the circular reference inside the function
 function attachEvents() {
  var element = document.getElementById(‘myID’);
  element.onclick = function() {
   //Remove element, so function can be collected by GC
   delete element;
   alert(“Element clicked”);
  }
 };
 attachEvents();
 
 << 요소에 function이 참조로 걸려 해제가 되지 않는 문제를 다루고 있습니다. >>


7. float 과 integer의 구분
 Example:
 var myNumber = 3.5;
 var myResult = 3.5 + 1.0; //We use .0 to keep the result as float
 Solution: don’t use decimals to “convert” numbers to floats.
 var myNumber = 3.5;
 var myResult = 3.5 + 1; //Result is 4.5, as expected
 
 << 자바스크립트 float 과 integer 구분이 없습니다. 모두 float 입니다. >>
 
8. with() 사용
 Example:
 team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
 with (team.attackers.myWarrior){
  console.log ( “Your warrior power is ” + (attack * speed));
 }
 Solution: don’t use with() for shortcuts. Only for context injection when you really need it.
 team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
 var sc = team.attackers.myWarrior;
 console.log(“Your warrior power is ” + (sc.attack * sc.speed));


 << with() 는 특별한 경우가 아니면 사용하지 말라는 내용입니다. 이유는 느리기 때문입니다. >>
 
9. 문자 조합을 이용한 setTimeout/setInterval
 Example:
 function log1() { console.log(document.location); }
 function log2(arg) { console.log(arg); }
 var myValue = “test”;
 setTimeout(“log1()”, 100);
 setTimeout(“log2(” + myValue + “)”, 200);
 Solution: never use strings for setTimeout()or setInterval()
 function log1() { console.log(document.location); }
 function log2(arg) { console.log(arg); }
 var myValue = “test”;
 setTimeout(log1, 100); //Reference to a function
 setTimeout(function(){ //Get arg value using closures
  log2(arg);
 }, 200);
 
 << 스트링 조합을 사용할 경우 웹브라우저 엔진이 새로운 function 을 만들때 매우 느려지기때문에
    이렇게 사용하지 말라고 말합니다. >>
 
10. 무거운 funcation에 대한 setInterval() 사용
 Example:
 function domOperations() {
  //Heavy DOM operations, takes about 300ms
 }
 setInterval(domOperations, 200);
 Solution: avoid setInterval(), use setTimeout()
 function domOperations() {
  //Heavy DOM operations, takes about 300ms
  //After all the job is done, set another timeout for 200 ms
  setTimeout(domOperations, 200);
 }
 setTimeout(domOperations, 200);


 <<  자바 스크립트 엔진은  대기열에 이미 다른 실행이있다면 다음 실행 대기열에 추가합니다.
  이럴경우 function 을 건너뛰거나 동시에 실행될 소지가 발생합니다. >>
 >>
11. this 의 오용
 - 예로 표현하기 어려움.
 * Regular function: myFunction(‘arg1’);
 this points to the global object, wich is window for all browers.
 * Method: someObject.myFunction(‘arg1’);
 this points to object before the dot, someObject in this case.
 * Constructor: var something = new myFunction(‘arg1’);
 this points to an empty Object.
 * Using call()/apply(): myFunction.call(someObject, ‘arg1’);
 this points to the object passed as first argument.
 
 << 여기에 대해서는 궁금하네요...접근에 대한 이슈같아 보입니다. >>
 
12. eval() 을 이용한 dynamic properties 접근
 Example:
 var myObject = { p1: 1, p2: 2, p3: 3};
 var i = 2;
 var myResult = eval(‘myObject.p’+i);
 Solution: use square bracket notation instead of eval()
 var myObject = { p1: 1, p2: 2, p3: 3};
 var i = 2;
 var myResult = myObject[“p”+i];
 
 << eval() 대신에 배열을 이용해서 접근하라는 말입니다. >>
 
13. undefined 를 사용하는 변수
 Example:
 if ( myVar === undefined ) {
  //Do something
 }
 Solution: use typeof when checking for undefined.
 if ( typeof myVar === “undefined” ) {
  //Do something
 }
 
 << undefined 확인하기위해서는 typeof 를 사용하라는 것입니다. >>
 


 

728x90

'프로그래밍 > 자바스크립트' 카테고리의 다른 글

quick menu 바  (0) 2013.07.19
javascript 브라우저 종류  (0) 2012.11.23
자주 쓰이는 JQuery Ajax 예제  (0) 2011.08.02
jQuery 요약  (0) 2011.08.02
자바스크립트 팁  (0) 2011.05.20

+ Recent posts