변수 선언
전역에 선언된 var 변수는 window속성으로 생성된다.
전역에 선언된 var 변수는 중복선언이 되어도 에러가 발생하지 않는다.
전역에 선언된 let 변수는 window속성으로 생성되지 않는다.
전역에 선언된 let 변수는 중복선언되면 에러가 발생한다.
let 변수는 해당 let이 속한 블록의 범위내에서 유효하다.
let a2 = 2;
let a2 = 'text2'; //에러발생
javascript에는 null 과 undefined가 있다.
null은 말그대로 값이 없다는 뜻이고
undefined는 값이 지정되지 않았다는 뜻으로 값이 없는지 있는지조차 모른다
null은 값이 없다는 것을 명시적으로 밝히기 위해 의도적으로 사용하는 것이고
undefined는 변수는 생성되었으나 변수의 값이 초기화되기 전 반환되는 값이다.
typeof null ==> Object
typeof undefined ==> undefined
Falsy & Truthy
false로 간주되는 값과 truth로 간주되는 값
falsy, truthy한 값은 논리형 타입으로 자동 변경되어 의도하지 않은 결과를 일으킬 수 있다.
-falsy values : 0, null, undefined, ''
let zeroNumber = 0;
let nullValue = null;
let emptyString = '';
let undefinedVar;
위 값들은 조건문과 같이 논리형을 필요로하는 곳에서 논리형으로 변경되어 반환된다.
if(!zeroNumber){
console.log('zeroNumber=false, !zeroNumber=true이므로 실행되는 코드');
}
-truthy values : 0이 아닌 숫자, emptyStr이 아닌 문자열
let zeroNumberStr = '0';
let boolStr = 'false';
let spaceStr = ' ';
let number = 213213;
let str='이름';
String 값이 '0'이더라도 0이라는 내용과 관계없이 emptyStr이 아니므로 truthy
Object 객체생성
1. 생성자 함수
let o1 = new Object();
o1.data=1;
o1.data2 = 2;
o1.cm = function(){};
o1 변수에 객체를 생성하고 o1에 data 변수를 만들어 1을 초기화 해준다.
자바에서는 객체에 필드가 있어야 값을 초기화할 수 있지만
자바스크립트에서는 객체의 멤버필드를 동적으로 생성할 수 있기 때문에
Object를 생성후 data, data2, cm 의 선언이 가능한 것이다.
이러한 방식은 같은 객체를 표현할때마다 갖는 프로퍼티가 달라질 수 있다.
자바의 클래스와 같이 같은 객체는 같은 프로퍼티를 갖게 하기 위해서 사용할 수 있는 방법
-학생 객체를 생성해서 반환해주는 function을 작성
function createStudent(id,name,kor,eng,math){
let studentObject={
id:id,
name:name,
kor:kor,
eng:eng,
math:math,
tot:0,
avg:0.0,
calculateTot:function(){this.tot=this.kor+this.eng+this.math},
calculateAvg:function(){this.avg=this.tot/3},
toString:function(){
document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.avg+" "+this.tot+" ");
}
};
return studentObject;
}
정해진 인자를 받고 정해진 프로퍼티를 갖는 student 객체를 생성해준다.
-Student 생성자 함수 작성
function Student(id,name,kor,eng,math){
this.id=id;
this.name=name;
this.kor=kor;
this.eng=eng;
this.math=math;
this.tot=0;
this.avg=0.0;
this.calculateTot=function(){
this.tot=this.kor+this.eng+this.math;
};
this.calculateAvg=function(){
this.avg=this.tot/3;
};
this.toString=function(){
document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.math+" "+this.tot+" "+this.avg);
};
}
Student('xxx','xman',12,23,20);//student는 window에
Student('yyy','yman',14,49,39);//student는 window에 y가x를 덮어버림
생성자 함수를 사용할 때 이런식으로 생성하면 생성된 Student는
window에 등록되고 window에 다시 등록하면 기존의 Student를 덮어버린다.
let studentObject1 = new Student('xxx','xman',12,23,20);
let studentObject2 = new Student('yyy','yman',14,49,39);
생성자함수의 생성시 new 예약어를 붙여준다.
new 예약어는 Object객체를 생성해주고 Object객체에 속성을 추가한뒤 객체를 반환해준다.
이러한 방식도 여전히 각 객체마다 동일한 함수를 가져야한다는 단점이 있다.
-Prototype을 사용한 방식
function Student(id, name, kor, eng, math) {
this.id = id;
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
this.tot = 0;
this.avg = 0.0;
}
Student.prototype = {
calculateTot: function() {
this.tot = this.kor + this.eng + this.math;
},
calculateAvg: function() {
this.avg = this.tot / 3;
},
toString: function() {
return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
}
}
new Student('xxx', '김', 23, 56, 78).calculateTot();
Student.prototype에 function들을 정의해준다.
function을 사용할 땐 student 객체에서 바로 .calculateTot()로 접근해주면 된다.
-class를 이용한 방식
class Student{
constructor(id,name,kor,eng,math){
this.id = id;
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
this.tot = 0;
this.avg = 0.0;
}
calculateTot(){
this.tot = this.kor + this.eng + this.math;
}
calculateAvg(){
this.avg = this.tot / 3;
}
toString(){
return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
}
}
사용법은 이전과 동일하다
-자바의 객체지향을 흉내낸 패키지 개념의 생성자
com={};
com.Student= function(id, name, kor, eng, math) {
this.id = id;
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
this.tot = 0;
this.avg = 0.0;
}
/************prototype[JSON][case 2]***********/
com.Student.prototype = {
calculateTot: function() {
this.tot = this.kor + this.eng + this.math;
},
calculateAvg: function() {
this.avg = this.tot / 3;
},
toString: function() {
return "[" + this.id + "]" + this.name + "," + this.kor + "," + this.eng + "," + this.math + "," + this.tot + "," + this.avg;
}
}
com이라는 객체를 생성하고
com 객체안에 Student 생성자를 만든다.
new com.Student('j','j',1,2,3)
생성할때도 com 객체를 붙여주어야 하고
student 객체에 접근할 때도 com을 통해 접근해야한다.
2. JSON 방식
let o2 = {
data:1,
data2:2,
cm: function(){}
}; //json
JSON표기법으로 객체를 생성할 수 있다
{
변수 : 값,
함수명 : 함수
}
Array 배열
1.Array객체 생성
let array1 = new Array();
array1.a = 1;
Array() 객체를 생성하면 Array 객체의 function들을 사용할 수 있다.
2.JSON 방식
let scoreArray=[34,56,78,90,100];
Object객체는 {...}로
Array 객체는 [...]로 표기한다.
객체를 담은 배열은 [ {...}, {...}, ...];
let studentArr = [
{
no:1,
name:"KIM",
score:34
},
{
no:2,
name:"LEE",
score:56
}
];
객체를 상수로 생성하는 경우
const studentObject1={
id:'xxx',
name:'sim',
kor:47,
eng:89,
math:99,
tot:0,
avg:0.0,
calculateTot:function(){this.tot=this.kor+this.eng+this.math},
calculateAvg:function(){this.avg=this.tot/3},
toString:function(){
document.write(this.id+" "+this.name+" "+this.kor+" "+this.eng+" "+this.avg+" "+this.tot+" ");
}
};
const는 상수이기 때문에 변경이 불가능하다.
여기서 상수는 studentObject1의 참조변수이지 studentObject1의 프로퍼티가 아니다.
즉 id, name, kor, ...등은 얼마든지 변경 가능하다.
studentObject1=studentObject2; 실행결과
studentObject1은 상수이기 때문에 studentObject2로 변경이 불가능하다.
studentObject1.id='zzz'; 실행결과
반면, studentObject1.id는 상수가 아니기 때문에 변경이 가능하다.
함수
자바스크립트에선 함수를 인자로 받고, 변수에 대입하거나 반환하는 것이 가능하다.
function func4(functionArg,funcArg){
let funcLet = functionArg();
return funcArg();
}
func4(
function(){
...
},
function(){
...
}
);
함수 선언 방법
이름이 존재하는 선언적 함수 선언
1. function name(param){...code...}
익명함수 선언
2. function (param){...code...}
3. (param) => {...code...}
4. param => {...code...}
익명함수의 선언과 실행
(function(){
document.write('익명함수가 실행<br>');
})();
(function(){...}) ();
익명함수를 선언하고 바로 (); 실행할 수 있다.
파라메터가 존재하지 않을 수 있고, 다수의 파라메터를 받을 수도 있다.
파라메터는 변수나 함수를 받을 수 있다. 표준자바스크립트 함수 (alert, confirm...)도 파라메터로 쓸 수 있다.
var alertVar = window.alert;
var confirmVar = confirm;
Closure 클로져
내부함수가 참조하는 외부함의 지역변수가 외부함수에 의해 내부함수가 반환된 이후에도 환경이 유지되는 것
function outer_function2(){
let outer2_var="outer2 로컬변수데이터";
return function(){
let inner2_var="inner2 로컬변수데이터";
document.write("익명 inner_function2--> outer2_var:"+outer2_var+"<br>");
document.write("익명 inner_function2--> inner2_var:"+inner2_var+"<br>");
};
}
let return_inner_function2=outer_function2();
return_inner_function2();
실행결과
//실행결과
//outer_function2() 실행이 끝나고 inner_function2를 반환받아서 실행하면 outer_function2의 변수와 inner_function2의 변수를 모두 사용할 수 있다.
DOM객체 찾기
-document.getElementById();
돔트리 전체에서 Id로 검색
-pE.getElementById();
pE노드의 하위 노드중에서 Id로 검색
DOM객체의 동적 생성
document.createElement("tagName");
let newDivE =document.createElement("div");
newDivE.setAttribute("id","newDiv"+count);
newDivE.setAttribute("style",`border: 1px dotted gold`);
태그 네임을 받아 원하는 객체를 생성할 수 있다.
생성된 객체에 setAttribute("attribute","value"); function으로 객체에 속성을 설정할 수 있다.
document.createTextNode(textMsgStr);
let newTextNode=document.createTextNode('textMessage');
텍스트 노드는 html의 텍스트 컨텐츠이다.
parentElement.appendChild(childElement);
let parentDivE = document.getElementById("parent");
parentDivE.appendChild(newDivE);
newDivE.appendChild(newTextNode);
P.appendChild(C); 는 P부모객체의 마지막 자식 노드에 C자식 객체를 붙여준다.
순서에 유의해야한다.
.insertBefore(추가할 노드, 기준노드) 메서드를 사용하면 위치를 어느정도 능동적으로 조정할 수 있다.
기준노드의 앞에 추가할 노드를 추가한다.
parentElement.removeChild(childElement);
parentDivE.removeChild(removeDivE);
P객체의 자식객체를 삭제한다.