본문 바로가기

FRONT-END/JAVASCRIPT

자바스크립트의 변수

반응형

자바스크립트의 기본형 typeof


number(숫자)

string(문자열)

boolean(이진 값)

undefined

null

symbol


자바스크립트느 기본형 변수들과 Object를 기초로하는 객체들로 구성된다.

특정 변수가 어떤 형태 인지 확인하는 연산자로 typeof가 있다.


undefined  - 정의되지 않는 값 또는 해당 값을 가진 변수

boolean - ture/false 값 또는 해당 값을 가진 변수

number - 숫자 값 또는 해당 값을 가진 변수

string - 문자열 값 또는 해당 값을 가진 변수

object - 객체 또는 객체를 저장하는 변수

function - 함수 또는 함수를 저장하는 변수

symbol - Symbol() 함수로 생성한 키


변수형에 따른 분기 처리

var myVariable = function(){

console.log("function");

};


if(typeof myVariable === "function") {

alert("Variable is function");

myVariable.call(this);

}else if(typeof myVariable ==="string"){

alert("Variable is string: "+myVariable);

}



console.log(typeof 3); //number

console.log(typeof "str"); //string

console.log(typeof {}); //object

console.log(typeof []); //object

console.log(typeof function (){}); //function

console.log(typeof null); //object


typeof 연산자


Table 35: typeof Operator Results
Type of valResult
Undefined"undefined"
Null"object"
Boolean"boolean"
Number"number"
String"string"
Symbol"symbol"
Object (ordinary and does not implement [[Call]])"object"
Object (standard exotic and does not implement [[Call]])"object"
Object (implements [[Call]])"function"
Object (non-standard exotic and does not implement [[Call]])Implementation-defined. Must not be "undefined""boolean""function""number""symbol", or "string".



null 검사 방법

if(myVariable !== null && typeof myVariable === "function") {

    //

}


또는 


if(!!myVariable && typeof myVariable === "function") {

    //

}



instaceof

어떠한 객체인지 확인하는 instanceof 연산자

리턴값은 true or false

(변수가 해당 클래스의 인스턴스인지 확인하는)


function Person(name, age){

this.name = name;

this.age = age;

}

var tomas  = new Person("tomas", 15);


console.log(tomas instanceof Person);  // true

console.log(tomas instanceof Object);  // true

console.log(typeof tomas);  // obejct


기본형을 instanceof로 연산시

console.log(true instanceof Boolean); //false

console.log(true instanceof Object); //false

console.log([0.1] instanceof Array); //true


var drink1 = new String("coffee");

var drink2 = "coffee";

console.log(drink1 == drink2); // true

console.log(drink1 instanceof String); //true

console.log(drink2 instanceof String); //false

console.log(drink2 instanceof Object); //false


기본형 문자열과 문자열 객체 비교

console.log(drink1 === drink2); // false

console.log(drink1.constructor == String); // true

console.log(drink2.constructor == String); // true


==비교연산자는  true

두 피연산자가 다른 형태일 때 대부분 비교를 위해 형 변환이 일어나서 같은 값으로 판단


===비교연산자는 false

형변환이 일어나지 않는 엄격한 비교를 수행하여 다른 값으로 판단


drink1은 Sring의 인스턴스

drink2는 기본형


constructor를 연산할 때 내부적으로 형 변황이 일어난 다음에 constructor에 접근한다.



GetValue (V)#

  1. ReturnIfAbrupt(V).
  2. If Type(V) is not Reference, return V.
  3. Let base be GetBase(V).
  4. If IsUnresolvableReference(V) is true, throw a ReferenceError exception.
  5. If IsPropertyReference(V) is true, then
    1. If HasPrimitiveBase(V) is true, then
      1. Assert: In this case, base will never be null or undefined.
      2. Let base be ToObject(base).
    2. Return ? base.[[Get]](GetReferencedName(V), GetThisValue(V)).
  6. Else base must be an Environment Record,
    1. Return ? base.GetBindingValue(GetReferencedName(V), IsStrictReference(V)) (see 8.1.1).
NOTE

The object that may be created in step 5.a.ii is not accessible outside of the above abstract operation and the ordinary object [[Get]] internal method. An implementation might choose to avoid the actual creation of the object.


  ToObject ( argument )#

The abstract operation ToObject converts argument to a value of type Object according to Table 13:

Table 13: ToObject Conversions
Argument TypeResult
UndefinedThrow a TypeError exception.
NullThrow a TypeError exception.
BooleanReturn a new Boolean object whose [[BooleanData]] internal slot is set to the value of argument. See 19.3 for a description of Boolean objects.
NumberReturn a new Number object whose [[NumberData]] internal slot is set to the value of argument. See 20.1 for a description of Number objects.
StringReturn a new String object whose [[StringData]] internal slot is set to the value of argument. See 21.1 for a description of String objects.
SymbolReturn a new Symbol object whose [[SymbolData]] internal slot is set to the value of argument. See 19.4 for a description of Symbol objects.
ObjectReturn argument.

ToObject 함수의 인자로 String기본형을 넘기면 새로운 String 객체를 생성하여 반환한다.



추가속성선언 여부

문자열을 생성하는 방법중 다른점

기본형은 추가 속성을 선언할 수 없다

var constructString = new String("tomas");

constructString.nickname = "tom";

console.log(constructString.nickname === "tom");


var primitiveString = "tomas";

primitiveString.nickname ="tom";

console.log(primitiveString.nickname === undefined);



하지만 prototype과 연계하면 자바스크립트만의 독특한 특징이 나타난다.

String.prototype.trim = function(){

return this.replace(/^\s+|\s+$/g, "");

}


console.log("    tomas    ".trim() === "tomas");


String.prototype에 함수를 추가로 구현하면 기본형에서도 해당 함수를 사용할 수 있게 된다.


출처-속깊은 자바스크립트 양성익 지음

반응형