브라우저에서 HTML, CSS를 동적으로 제어하기 위해 만들어진 언어
Node.js : 서버측에서 실행되는 JS
UI : User Interface
API : Application Programing Interface
코드의 형태를 띄고 있는 인터페이스. ex) alert Interface
복잡한 코드를 띄고 있음에도 불구하고 API를 통해 보다 간단한 개발이 가능하도록 해주는 인터페이스.
Document → DOM (Document Object Model) → Window 순으로 서칭 범위를 넓혀가며 필요한 기능 찾기
Index | Node.js v19.4.0 Documentation
alert(typeof "1");
alert(1=='1'); // true
alert(1==='1'); // false
// ===같은 경우 값과 데이터형이 모두 정확히 일치해야 true를 반환한다.
-------------------------------
alert(0 === -0); // true
alert(NaN === NaN); // false
-------------------------------
alert(1!=1); // false
alert(1!==1); // false
var i = 1;
for(var i = 0; i < 10; i++) {
alert(i);
}
while(i < 10) {
alert(i);
i++;
}
// 함수 선언 방법 1
function numbering(start) {
while(start < 10) {
console.log(start);
start++;
}
return 'successful';
}
// 함수 선언 방법 2
numbering = function() {
while(start < 10) {
console.log(start);
start++;
}
return 'successful';
}
// 정의와 호출을 같이 하는 방식...이름이 필요 X -> 익명함수
// 1회성으로 작성할 때 사용하는 테크닉
(function() {
while(start < 10) {
console.log(start);
start++;
}
return 'successful';
})();
var id = ['1', '2', '3']
alert(id[0]);
alert(id[1]);
alert(id[2]);
---------------------------
// 배열에 원소 추가하기
id.push('4'); // 끝에 4 추가
id.concat(['5', '6']); // 끝에 5, 6 추가
id.unshift('0'); // 배열의 처음에 0 추가, 기존 값들의 색인(index)은 1씩 증가(shift)
id.splice(2,0,'1.5'); // 2번째 인덱스에 0개를 삭제한 후 1.5를 끼워넣는다.
---------------------------
id.pop(); // 맨 끝 원소 삭제
---------------------------
id.sort(); // 오름차순 정렬
id.reverse(); // 내림차순 정렬
// 객체 선언 방법1
var grades = {'a' : 88, 'b' : 89, 'c' : 90};
// 객체 선언 방법2
var grades = {};
grades['a'] = 88;
grades['b'] = 89;
grades['c'] = 90;
//객체 선언 방법3
var grades = new Object();
grades['a'] = 88;
grades['b'] = 89;
grades['c'] = 90;
//객체 호출방법
alert(grades.a); // 88
alert(grades['a']); // 88
var grades = {
'list' : {'a' : 100, 'b' : 90, 'c' : 80}
'show' : function() {
alert('Hello world');
}
'this' : function() {
alert(this); // this : 이 함수가 속해있는 객체를 가리키는 변수
}
}
alert(grades['list']['a']); // 100
**alert(grades['show']); // function() { ~~ }
alert(grades['show']()); // Hello world**
var grades = {
'list' : {'a' : 100, 'b' : 90, 'c' : 80}
'show' : function() {
for(var level in this.list) {
console.log(level, this.list[level]);
}
}
}
<script src="greeting.js"> </script>
js파일을 따로 빼서 만듦으로서 유지보수에 적합하게 만든다. (모듈화)
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
// 정규표현식 표현방법 1
var pattern = /a/; // / 사이의 패턴을 찾는다.
// 방법 2
var pattern = new RegExp('a'); // Regular Expression(a)를 찾는 객체를 하나 만듦.
pattern.exec('abcde'); // ['a'] // abcde 중에 a를 찾는 것. 없으면 null을 리턴.
pattern.test('abcde'); // true - a 존재함
pattern.test('bcde'); // false - a 존재하지 않음
var str = 'abcdef';
str.replace(pattern, 'A'); // 'Abcdef'
var oi = /a/i; // i 는 대소문자 구분을 하지 않고 찾는다.
var xg = /a/;
"abcdea".match(xg); // ['a']
var og = /a/g; // g 는 중복을 허용한다.
"abcdea".match(og); // ['a', 'a']
var ig = /a/ig;
"AbcdeAa".match(ig); // ['A', 'A', 'a']
(\w+)\s(\w+) ... 하나 이상의 문자(a-Z,0-9)그룹 후 공백 후 하나~
ex) A B | 0 r | 등등
var pattern = /(\w+)\s(\w+)/; // $1 : coding, $2 : everybody
var str = "coding everybody";
var result = str.replace(pattern, "$2, $1"); // everybody, coding
즉, 그룹을 지정하고 그 그룹을 가져와 사용한다 : 캡쳐
var vscope = 'global';
function fscope() {
var vscope = 'local';
alert(vscope);
}
fscope(); // local
alert(vscope); // global
function fscope() {
vscope = 'local';
alert(vscope);
}
fscope(); // local
alert(vscope); // local
var를 사용하지 않고 선언하면 global 선언이 되므로 값이 변경된다.
var선언을 습관화하자. for 코드의 재사용성
JS는 함수에 대해서만 유효 범위를 제한한다. for 문이나 기타 {} 안의 변수들은 다른 언어들과 달리 함수의 {}만 아니면 사용 가능하다는 것이다.
var i = 5;
function a() {
var i = 10;
b();
}
function b() {
alert(i);
}
a(); // 5
Ajax - Asynchronous Javascript And XML
리로딩을 하지 않고 서버와 웹 브라우저가 내부적으로 소통하는 기술
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$.get(
'http://~~',
function(result) { // $.get이 위 url에서 가져온 데이터를 result로 function인자에 넣어줌.
console.log(result); // 사용자에게 어떤 처리를 위임한다 -> 콜백
}, 'json'
);
</script>
Closure
내부함수가 외부함수의 맥락에 접근할 수 있는 것을 가리킨다.
function outter() {
var title = 'coding everybody';
return function() {
alert(title);
}
}
inner = outter();
inner(); // coding everybody
function factory_movie(title) {
return {
get_title : function() {
return title;
},
set_title : function(_title) {
title = _title;
}
}
}
ghost = factory_movie('Ghost in the shell');
matrix = factory_movie('Matrix');
alert(ghost); // Ghost in the shell
alert(matrix); // matrix
var arr = []
for(var i = 0; i < 5; i++) {
arr[i] = function(id) {
return function() {
return id;
}
}(i);
}
for (var index in arr) {
console.log(arr[index]());
}
유사 배열 성격을 띈 객체
o1 = {val1:1, val2:2, val3:3}
o2 = {v1:10, v2:50, v3:100, v4:25}
function sum() {
var _sum = 0;
for(name in this) {
_sum += this[name];
}
return _sum;
}
alert(sum.apply(o1)); // 6
alert(sum.apply(o2)); // 185
생성자 함수는 일반함수와 구분하기 위해서 첫글자를 대문자로 표시한다.
function Person(name){
this.name = name;
this.introduce = function(){
return 'My name is '+this.name;
}
}
var p1 = new Person('egoing'); // egoing
document.write(p1.introduce()+"<br />");
var p2 = new Person('leezche');
document.write(p2.introduce()); // leezche
JS에서 모든 객체는 기본적으로 전역 객체의 property이다. 객체를 명시하지 않으면 암시적으로 window의 프로퍼티로 간주된다. 전역객체의 이름도 호스트환경에 따라서 다른데, 웹브라우저에서 전역객체는 window이지만 node.js에서는 global이다.
function func(){
alert('Hello?');
}
func(); // Hello
window.func(); // Hello
var o = {'func':function(){
alert('Hello?');
}}
o.func(); // Hello?
window.o.func(); // Hello?
결국 함수도 전역 객체의 프로퍼티이기 때문에 여기서 this는 window라는 전역 객체를 가리킨다. Node.js에서는 global
function func(){
if(window === this){
document.write("window === this");
}
}
func();
var 0 = {
func : function() {
if (o === this) {
document.write("o === this");
}
}
}
o.func();
var funcThis = null;
function Func() {
funcThis = this;
}
var o1 = Func(); // 함수 저장 -> 함수에서 this 호출 -> 전역 객체인 window
if (funcThis === window) {
document.write('window </br>');
}
var o2 = new Func(); o2 객체 저장 -> 객체에서 메소드 호출 -> this는 o2를 가리킴
if(funcThis === o2) {
document.write('o2 </br>');
}
function sum(x,y) {return x+y;}
var sum2 = new Function('x', 'y', 'return x+y;');
sum2(1,2); // 3
// 함수 Literal을 만들어 준다. (리터럴:보다 편한 문법체계, 객체리터럴, 배열리터럴 등)
var o = {}
var p = {}
function func() {
switch(this) {
case o:
document.write('o<br />');
break;
case p:
document.write('p<br />');
break;
case window:
document.write('window<br />');
break;
}
}
func();
func.apply(o);
func.apply(p);
// 즉, 함수는 자바와 달리 객체에 소속되지 않고, window객체, o객체, p객체에 apply된다.
function Person(name) {
this.name = name;
}
Person.prototype.name = null;
Person.prototype.introduce = function() {
return 'My name is ' + this.name;
}
function Programmer(name) {
this.name = name;
}
**Programmer.prototype = new Person();
// 상속을 위해서는 생성자의 프로토타입에 상속받고자 하는 객체를 생성해주면 된다.
Programmer.prototype.coding = function() {
return "hello world";
} // 상속된 객체에서 함수를 추가한 케이스. 마찬가지로 prototype 사용.**
function Designer(name) {
this.name = name;
}
Designer.prototype = new Person();
Designer.ptototype.design = function() {
return "beautiful";
}
var p1 = new Programmer('john');
document.write(p1.introduce() + "<br />");
document.write(p1.coding() + "<br />");
var p2 = new Designer('sarah');
document.write(p2.introduce() + "<br />");
document.write(p2.design() + "<br />");
표준 내장 객체를 상속받아 커스텀 메소드들을 작성함으로서 확장을 이룰 수도 있다.
모든 객체는 기본적으로 object를 상속받고 있으며, 따라서 object를 확장할 수도 있다.
hasOwnProperty는 인자로 전달된 속성의 이름이 객체의 속성인지 여부를 확인한다. 만약 prototype으로 상속 받은 객체라면 false를 리턴한다.
객체와 비객체(Primitive type)로 나눌 수 있다.
var a = 1;
var b = a;
b = 2;
console.log(a); // 1
var a = {'id':1}; // 데이터형이 객체이므로 참조형이다. 즉, 값이 바뀌면 같이 바뀐다.
var b = a;
b.id = 2;
console.log(a.id); // 2
var a = 1;
function func(b){
b = 2;
}
func(a);
console.log(a); // 1
var a = {'id':1};
function func(b){
b = {'id':2}; // b에 새로운 객체를 전달했으므로 a는 상관이 없다.
}
func(a);
console.log(a.id); // 1
var a = {'id':1};
function func(b) {
b.id = 2;
}
func(a);
console.log(a.id); // 2
<input type="button" value="hi" onclick="alert('hi')">
<input type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value === 'night') {
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
} else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
}
">
함수를 콜할 때 this 를 매개변수로 넣으면 이는 함수가 속한 태그를 넘긴다.
만약 매개변수가 없다면 함수 내 this는 전역 객체를 가리키게 된다.
<input type="button" value="night" onclick="
nightDayHandler(this);
">
function nightDayHandler(self) {
var target = document.querySelector('body');
if(self.value === 'night') {
target.style.backgroundColor = 'black';
target.style.color = 'white';
self.value = 'day';
<script src="colors.js"> // color관련 작업 코드들을 독립 파일로 빼서 만든다.
</script>
html을 구성하는 element들을 node 개념으로 바라보고, 더 나아가 객체로 대하는 방식