2013년 12월 11일 수요일

JavaScript study 중 데이터 형, scope 관련 문법 중 특이사항 정리

이전 블로그에서 이전 함 (원본 글 2013/12/11 작성)

[데이터 타입]

- undefined : 변수를 선언 후 아무 값도 지정하지 않은 상태
- null : 키워드, 객체가 아무것도 없음을 나타냄
- infinity, Nan : 숫자에서 무한한 수와 숫자가 아님을 나타냄, isFinite(), isNan() 함수로 비교 가능
- false를 나타내는 값들 : false, 0, null, undefined, Nan, ""
  : infinity인 경우 무한한 값을 나타내므로 true이다.

===, !==
 : 값을 비교하는 '==', '!='와는 달리 두 변수의 데이터 타입까지 비교한다. javascript의 변수는 대입되는 값에 따라서 데이터 형이 결정되므로 유용하게 쓰임.

&&, ||
 : || => 왼쪽 값이 참일때는 왼쪽 값을 리턴하고 거짓일 경우에는 오른쪽 값을 리턴한다.
   && => 왼쪽값이 거짓일때는 왼쪽 값을 리턴하고 참일 경우에는 오른쪽 값을 리턴한다.


var a = ("test one" || "test two"); // a is "test one"
var b = ("test one" || ""); // b is "test one"
var c = (0 || "test two"); // c is "Test two"
var d = (0 || false); // d is false
 var a = ("test one" && "test two"); // a is "test two"
var b = ("test one" && ""); // b is ""
var c = (0 && "test two") // c is 0

Advanced Javascript: Logical Operators and truthy / falsy
 데이터 타입 및 비교 관련 여러 case에 대해서 설명하고 있음.


[Scope]

- 변수를 함수내에서 var로 선언하지 않으면 전역 변수, var로 선언하면 지역변수
- Lexical 특성
 실행시, 각 문장이 참조하는 변수는 렉시컬 환경에서 정의한, 즉 "코드 그대로의 환경"을 기준으로 정의한 변수 스코프에서 검색한다.

var a = 0; 
console.log("1. a= " + a);                //==> 0

function test() {
console.log("2. a= " + a);    //==> undefined, 함수내 a가 정의되어 전역변수로 취급 안됨
var a = 1;
console.log("3. a= " + a);       //==> 1
}
console.log("4. a= " + a);               //==> 0
test();
console.log("5. a= " + a);               //==> 0

(출력)

- 변수가 저장되는 메모리 영역
 : 변수스코프(함수 내 var 변수), 프로토타입 객체(인스턴스가 상속), 공개변수영역, 인스턴스

- 프로토타입 관련

 . JavaScript에서 instantiate된 객체들이 함께 공통으로 참조하는 공간으로 모든 객체들의 속성을 변경하고자 할 경우 prototype을 수정해야 한다. 자세한 것은 아래 링크 참조

모든 Javascript 객체가 상속받는 Object 객체의 기본 속성은 다음과 같다.

Object.prototype.constructor
 : Specifies the function that creates an object's prototype.
Object.prototype.__proto__ 
 : Points to the object which was used as prototype when the object was instantiated.
Object.prototype.__noSuchMethod__ 
 : Allows a function to be defined that will be executed when an undefined object member is called as a method. 

 <!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">

function Person(name) {
this.name = name;
}

function Korean(name, city){
Person.apply(this, [name]);
this.city = city;
}

Korean.prototype = new Person();

Korean.prototype.constructor = Korean;
Korean.prototype.nationality = "korean";

var p1 = new Person("Hong");
var p2 = new Person("Kim");

p1.age = 23;
Person.prototype.species = "human";

console.log("[Person] p1");
for(var key in p1){
console.log("key=" + key + ", value=" + p1[key]);
}

console.log("\n[Person] p2");
for(var key in p2){
console.log("key=" + key + ", value=" + p2[key]);
}

console.log("\n[Korean] p3");

var p3 = new Korean("Lee", "seoul");

for(var key in p3){
console.log("key=" + key + ", value=" + p3[key]);
}

</script>
</head>
<body>

</body>
</html>

 [Person] p1
key=name, value=Hong 3_inheritance.html:32
key=age, value=23 3_inheritance.html:32
key=species, value=human 3_inheritance.html:32
key=name, value=Kim 3_inheritance.html:37
key=species, value=human 3_inheritance.html:37
key=name, value=Lee 3_inheritance.html:45
key=city, value=seoul 3_inheritance.html:45
key=constructor, value=function Korean(name, city){ Person.apply(this, [name]); this.city = city; } 3_inheritance.html:45
key=nationality, value=korean 3_inheritance.html:45
key=species, value=human 3_inheritance.html:45


Korean {name"Lee"city"seoul"nameundefinedconstructorfunctionnationality"korean"}
  1. city"seoul"
  2. name"Lee"
  3. __proto__Person
    1. constructorfunction Korean(name, city){
    2. nameundefined
    3. nationality"korean"
    4. __proto__Person
      1. constructorfunction Person(name) {
      2. species"human"
      3. __proto__Object
        1. __defineGetter__function __defineGetter__() { [native code] }
        2. __defineSetter__function __defineSetter__() { [native code] }
        3. __lookupGetter__function __lookupGetter__() { [native code] }
        4. __lookupSetter__function __lookupSetter__() { [native code] }
        5. constructorfunction Object() { [native code] }
        6. hasOwnPropertyfunction hasOwnProperty() { [native code] }
        7. isPrototypeOffunction isPrototypeOf() { [native code] }
        8. propertyIsEnumerablefunction propertyIsEnumerable() { [native code] }
        9. toLocaleStringfunction toLocaleString() { [native code] }
        10. toStringfunction toString() { [native code] }
        11. valueOffunction valueOf() { [native code] }
        12. get __proto__function __proto__() { [native code] }
        13. set __proto__function __proto__() { [native code] }

참고로 위에서 만들어진 p3 객체를 보면
name, nationality 속성을 가진 Person 객체를 prototype으로 참조하고 있고 이는
species 속성을 가지는 Person prototype을 참조하고 있고
결국은 Object 객체를 참조하고 있다.

나도 자세히는 모르겠으나 javascript prototype 검색이나 아래글 참고

[Introduction to Object-Oriented JavaScript]

[Details of the object model]

  

- 자바스크립트는 함수는 argument의 개수가 일치하지 않아도 된다.
  : Arguments 객체 => arguments.length, arguments.callee
  : 덕분에 JavaScript에서는 method overloading 불가

 <!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
var add = function() {
var sum = 0;

//console.log(arguments.length);
for ( var name in arguments) {
sum = sum + arguments[name];
}
return sum;
}

console.log(add(1));
console.log(add(1, 2));
console.log(add(4, 6, 9, 2));

var fact = function(n) {
var self = arguments.callee;
if (n == 0) {
return 1;
} else {
return (n * self(n - 1));
}
};

console.log(fact(3));
console.log(fact(10));
</script>
</head>
<body>

</body>
</html>

[참고]

Javascript 기본 개념 설명

Javascript 특성을 잘 정리함.

렉시컬(lexical) 특성
황정식|조회 12|추천 0|2013.05.19. 19:15


댓글 없음:

댓글 쓰기