function sum(a,b){
console.log(a+b);
}
sum(2,3);
// 5
이 때
a와 b를 parameter(매개변수),
2와 3을 argument(인자)라고 한다.
인자는 array 형태의, 함수의 객체인데 실제 array랑은 다르다는 것에 주의하자.
원칙은 왼쪽부터 순서대로 연산된다.
function sum(left, right){
document.write('<div style=color:red>'+left+right+'</div>');
}
sum(2,3);
이 경우 붉은색 23이 출력된다.
주의해야 할 점은 string+number=number라는 점이다.
console.log(2+'3');
// 23
함수 실행을 종료하고 return 이하의 값을 출력함. 조건문이나 복잡한 식 사용시 유용할 듯 하다.
function sum(left, right){
return left+right;
}
document.write('<div style="color:red">'+sum(2,3)+'</div>');
이 경우 출력되는 값은 붉은색 5이다.
순서대로 정보가 저장되는 array는 [대괄호]를 쓰지만,
object는 순서와 상관없이 정보를 저장하며 {중괄호}를 쓴다.
var coworkers = {
"programmer" : "Alice",
"designer" : "Ethan"
};
document.write("Programmer : "+coworkers.programmer+"<br>");
document.write("Designer : "+coworkers.designer);
/*
Programmer : Alice
Designer : Ethan
*/
여기에서 coworkers는 object(객체)이고, programmer, designer같은 것들은 객체에 소속된 property(변수)라 한다.
만일 property를 추가하고 싶다면 다음과 같이 코드를 추가하자.
coworkers.planner = "Sue";
coworkers["chief producer"] = "Clare";
여기서 .은 object access operator인데 그것을 [대괄호]로 대신 넣을 수 있다.
for문과 변수를 통해 coworkers의 데이터를 꺼내올 수 있다.
for (var key in coworkers) {
document.write(key + "<br>");
}
/*
programmer
designer
planner
chief producer
*/
이를 활용하여 복잡한 코드를 간단하게 줄일 수 있다.
for (var key in coworkers) {
document.write(key + " : " + coworkers[key] + "<br>");
}
/*
programmer : Alice
designer : Ethan
planner : Sue
chief producer : Clare
*/
coworkers.showAll = function(){
};
function showAll(){
};
var showAll = function(){
};
이 세 개의 구문은 동일한 효과를 지닌다(물론 완전히 같은 것은 아니다.)
coworkers.showAll = function(){
for (var key in this){
document.write(key+' : '+this[key]+'<br>');
}}
coworkers.showAll();
// 이처럼 coworkers대신 this를 써서 단점을 줄일 수 있다.
위의 showAll처럼 객체에 소속된 함수를 method라고 하는데 이는 4-2.에서 썼던 것과 동일한 효과를 볼 수 있다. 다만 이 경우 메서드가 객체의 모든 데이터를 서술하게 되어 있어, 해당 메서드식까지 전부 노출된다는 단점이 있다.
var target = document.querySelector("body");
var Body = {
setColor: function (color) {
target.style.color = color;
},
setBackgroundColor: function (color) {
target.style.backgroundColor = color;
}
}
여러 개의 property를 사용할 때는 꼭 ,를 넣자. 반드시!
CSS와 마찬가지로, <script>와 </script> 사이의 코딩을 따로 빼어 파일명.js로 파일을 생성한다.
→남은 <script>를 <script src="파일명.js">로 바꾸어주면 끝
jQuery를 쓸 문서로 가서 위의 <script src="파일명.js"> 윗줄에 CDN코드를 삽입한다.
이로써 js파일에 쓴 jQuery 언어를 해당 문서에 적용할 수 있게 된다. 그리하여
var alist = document.querySelectorAll("a");
var i = 0;
while (i < alist.length) {
alist[i].style.color = color;
i = i + 1;
}
를
$("a").css("color", color);
로 간단하게 코딩할 수 있게 된다.