2.5 자바스크립트 함수 오버로딩에 관한 두 가지 예
<script type="text/javascript">
function sendMessage(msg, obj){
if(arguments.length == 2){
obj.alert(msg);
}else{
alert(msg);
}
}
sendMessage("Hello, World!");
sendMessage("How ar you?", window);
//전달 인자를 여러 개 받아 배열을 만들어 반환하는 함수
function makeArray(){
var arr = [];
for(var i=0 ; i<arguments.length; i++){
arr.push(arguments[i]);
}
return arr;
}
</script>
2.7 객체의 타입을 결정하는데 typeof를 사용한 예
<script type="text/javascript">
if(typeof num == 'string'){
num = parseInt(num);
}
if(typeof arr == 'string'){
arr = arr.split(",");
}
alert(msg);
</script>
2.8 객체의 타입을 결정하는데 constructor 프로퍼티를 사용하는 예
<script type="text/javascript">
if(num.constructor == String){
num = parseInt(num);
}
if(str.constructor == Array){
str = str.join(',');
}
alert(msg);
</script>
2.10 자바스크립트에서 변수 유효범위가 어떻게 작동하는지 보여주는 예
<script type="text/javascript">
var foo = "test";
//function이 아니라 if 문이다.
if(true){
var foo = "new test";
}
alert(foo=="new test");
//function 이기 때문에 old test가 된다.
function test(){
var foo = "old test";
}
test();
alert(foo == "new test");
// 모든 변수는 그저 windows 객체의 프로퍼티이다.
var test = "test";
alert(window.test == test);
</script>
2.13 클로저가 어떻게 코드의 의미를 명료하게 만드는지 보여주는 두가지 예
<script type="text/javascript">
var obj = document.getElementById("main");
obj.style.border = "1px solid red";
setTimeout( function(){obj.style.display ='none';},1000);
function delayedAlert(msg, time){
setTimeout( function(){alert(msg);},time);
}
delayedAlert("Welcome!", 2000);
</script>
2.14 클로저로 함수를 커링하는 예
<script type="text/javascript">
function addGenerator(num){
return function(toAdd){
return num+toAdd;
}
}
var addFive = addGenerator(5);
alert(addFive(4) == 9);
</script>
2.15 변수들을 전역 유효범위에서 볼 수 없게 익명 함수를 사용하는 예
<script type="text/javascript">
(function (){
var msg = "Thanks for visiting!";
window.onunload = function(){
alert(msg);
};
}());
</script>
2.16 한 콘텍스트 안에서 함수를 사용한 후 콘텍스트를 다른 변수로 바꾸는 예
<script type="text/javascript">
var obj = {
yes : function(){
//this = obj
this.val = true;
},
no : function(){
this.val = false;
}
};
alert(obj.val == null);
obj.yes();
alert(obj.val == true);
window.no = obj.no;
window.no();
alert(obj.val == true);
alert(window.val == false);
</script>
2.18 함수 콘텍스트를 바꾸는 예
<script type="text/javascript">
function changeColor(color){
this.style.color = color;
}
changeColor("white");
var main = document.getElementById("main");
changeColor.call(main, "black");
function setBodyColor(){
changeColor.apply (document.body, arguments);
}
setBodyColor("black");
</script>
2.19 간단한 객체를 하나 생성하고 프로퍼티를 설정하는 두가지 예
<script type="text/javascript">
var obj = new Object();
obj.val = 5;
obj.click = function(){
alert("hello");
}
var obj = {
val : 5,
click : function(){
alert("hello");
}
}
</script>
2.20 간단히 객체를 하나 생성하고 사용하기
<script type="text/javascript">
// 이름을 하나 받아서 현재 콘텍스트에 저장하는 간단한 함수
function User(name){
this.name = name;
}
var me = new User("My name");
//이름이 me의 프로퍼티로 설정된 것을 볼 수 있다.
alert(me.name == "My name");
//me가 User 객체의 인스턴스임을 알 수 있다.
alert(me.constructor == User);
alert(me.constructor);
//단순히 보면 User가 함수이므로 함수 취급을 하면 어떨까?
User("Test");
//이 함수의 this 콘텍스트가 설정되지 않았기 때문에
//콘텍스트는 기본적으로 전역변수 'window'가 된다.
//그 결과 주어진 이름과 window.name이 같아진다.
alert(window.name == "Test");
</script>
2.21 constructor 프로퍼티를 사용하는 예
<script type="text/javascript">
function User(){}
var me = new User();
//첫 번째 User 객체의 constructor를 참조하여 새로운 User 객체를 생성한다.
var you = new me.constructor
//실제로 constructor가 같음을 알 수 있다.
alert(me.constructor == you.constructor);
</script>
2.22 prototype 객체를 통해 추가한 메서드를 갖는 객체의 예
<script type="text/javascript">
function User(name, age){
this.name = name;
this.age = age;
}
User.prototype.getName = function (){
return this.name;
};
User.prototype.getAge = function (){
return this.age;
};
var user = new User("Bob", 33);
alert(user.getName() == "Bob");
alert(user.getAge() == 33);
</script>
2.23 생성자 함수에서만 사용할 수 있는 private 메서드 예
//교실을 표현하는 객체 생성자
function Classroom(students, teacher){
//수업을 듣는 모든 학생의 정보를 출력하는 private 메서드
function disp(){
alert(this.names.join(","));
}
//수업 정보를 public 객체 프로퍼티에 저장한다.
this.students = students;
this.teacher = teacher;
//오류를 출력하기 위해 private 메소드를 호출한다.
disp();
}
var cls = new Classroom(["scott","tiger","lion"], "Mr Smith");
//disp는 이 객체의 public 프로퍼티가 아니기 때문에 실패한다.
cls.disp();