- Object의 prototype을 통하여 확장을 하지마라
- 예를 보자
두번째 Object.prototype.e 를 확장하면 모든 오브젝트에 e="E"가 불필요하게 반영된다. 즉 모든 오브젝트에 상속된다
var obj = {a: "A", b: "B", c: "C", d: "D"};for (var key in obj) { alert(key +': '+obj[key]); //displays "a: A", "b: B", "c: C", "d: D"}Object.prototype.e = "E";for (var key in obj) { alert(key +': '+obj[key]); //displays "a: A", "b: B", "c: C", "d: D", "e: E"}var obj2 = {a2: "A2", b2: "B2", c2: "C2", d2: "D2"}; for (var key in obj2) { alert(key +': '+obj2[key]); //displays "a2: A2", "b2: B2", "2c: C2", "d2: D2", "e: E"}
- 상속의 방법
function Person(name, sex) {
Person.prototype.populationCount++; Person.prototype.getName=function(){ return name }; Person.prototype.getSex=function(){ return sex }; Person.prototype.setSex=function(newSex){ sex = newSex; }; Person.prototype.die=function(){ Person.prototype.populationCount -- ; };}Person.prototype.populationCount=0;var rob = new Person('Rob','male');var jeanie = new Person('Jeanie','female');alert(rob.populationCount); // displays 2//the following creates a new public property for rob and sets it to 12rob.populationCount+=10;alert(rob.populationCount); //displays 12alert(jeanie.populationCount); //still displays 2Child.prototype = Object.create(Person.prototype);Child.prototype.constructor = function Child(name, sex, age) { //call the parent constructor Person(name, sex); Child.prototype.getAge = function() { return age; };}var child = new Child('Ralph', 'male', 3);alert(child.getName()); //displays "Ralph"alert(child.getAge()); //displays 32. Global Namespace에 의한 오염
- 보통 var를 사용하지 않고 x=2 처럼 하면 window.x=2가 되어 전역영역을 오염시킨다. 따라서 변수선언시 반드시 var 를 사용한다
- Group 변수를 통해서 오염을 방지하자
var Finance = {};
Finance.INTEREST_RATE = 2.5;Finance.calcAnnualizedInterest(startVal, endVal) { //...}- 또는 ECMAScrpt 5 "use strict"를 script 맨위체 포함시킨다. 또는 function 안에 놓고 제한된 scope에서 strict mode를 사용할 수도 있다
function strictFunc(){
"use strict"; // code ...}- 예를 보자
i 의 결과값으로 5가 나온다. Global Namespace를 오염시키는 function - foo, bar -, variable - i - 같은 것은 절대 사용하지 말자
function foo() { return 1; }
function bar() { for (i=0; i<5; i++) {} }
i = foo();
bar();
3. True, False에 대한 부적절한 사용에 의한 오염
- 자바스크립트에서 zero (0), empty string (""), null, undefined, NaN 은 모둔 false 값이다
- 비교문이나 루프문에서 조건 사용시 축약한다
// Anti-Pattern
if (testString != undefined && testString != '') {
//do something}
// 변경 : 위 조건절과 동일
if (!testString) {
//do something}- ===, ==! 를 항상 사용한다
// 주의
var zero = 0;
if (zero === false) { // doesn't execute because zero is 0, not false}<참조>
- 원문 : Three JavaScript Anti-Patterns and How to avoid them
- Anti-Patterns를 피하고 성능을 향상시키는 방법들 : Slide 및 동영상
'Languages > JavaScript' 카테고리의 다른 글
| [JavaScript] Design Pattern - Module Pattern (0) | 2013.09.07 |
|---|---|
| [JavaScript] Design Pattern - Constructor Pattern (0) | 2013.09.07 |
| [JavaScript] 김영보선생님의 객체지향 이야기 (0) | 2013.06.28 |
| [JavaScript] 배우는 방법 (0) | 2013.02.20 |
| [JavaScript] var _this = this 의미 배우기 (1) | 2013.01.27 |
