ex3 ) 함수로 만들기
function makeStudent(name, age, kor, math, eng){
var stu={};
stu.name = name;
stu.age = age;
stu.kor = kor;
stu.math = math;
stu.eng = eng;
return stu;
}
var hong = makeStudent('퉁퉁이', 23, 50, 30, 40);
-----------------------------------------------------------------------------------------
자바스크립트 기능을 가지고 생성자를 흉내!
function makeStudent(name, age, kor, math, eng){
var stu={
"name" : name,
"age" : age,
"kor" : kor,
"math" : math,
"eng" : eng,
"getAverage" : function(){
return (kor + math + eng ) / 3;
}
};
return stu;
}
var hong = makeStudent('통통이', 23, 50, 30, 40);
alert("이름 : " + hong.name + "\n나이 : " + hong.age + "\n점수 :" + hong.getAverage());
----------------------------------------------------------------------------------------------
생성자함수! ( 사실 생성자함수라는게 따로 존재하는 개념이 아님! )
함수에서 this키워드를 이용해 속성을 추가하면
new 연산자를 통해 함수를 호출하면 this키워드에 추가한 속성들로 이뤄진 객체가 만들어짐
function Student(name, age, kor, math, eng){
this.name = name;
this.age = age;
this.kor = kor;
this.math = math;
this.eng = eng;
this.getAverage = function(){
return (kor + math + eng) / 3;
}
}
var hong = new Student('퉁퉁이', 23, 50, 30 , 40); // new를 사용하여 값을 넣으면 새로운 객체가 생성!
alert("이름 : " + hong.name + "\n나이 : " + hong.age + "\n점수 :" + hong.getAverage());
함수에서 this키워드를 이용해 속성을 추가하면
new 연산자를 통해 함수를 호출하면 this키워드에 추가한 속성들로 이뤄진 객체가 만들어짐
new 키워드를 사용하지 않았을때
this키워드는 window객체를 나타냄
-> 함수를 실행하는 동안 window객체에 속성을 추가하게 됨
new 키워드를 사용
함수가 실행될때 새로운 객체를 위한 공간을 만들고 this키워드가 해당 공간을 의미
--------------------------------------------------------------------------------------------------
태그영역에 마우스가 들어가면 빨간색이 됬다가 마우스가 나가면 다시 검은색이 되는 예제
window.onload = function(){
var h1 = document.getElementById('header');
h1.onmouseout = function(){
h1.style.color = 'black';
}
h1.onmouseenter = function(){
h1.style.color = 'red';
}
}
-------------------------------------------------------------------------------------------------------
함수로 따로만들어서 헤드에서 함수를 불러주는 방법
제목태그에 마우스를 가져가면 팝업창이뜨는 예제
window.onload = function(){
var h1 = document.getElementById('header');
}
function doSomething(){
alert('hello');
}
</script>
<body>
<h1 id="header" onmouseenter="doSomething()">제목태그</h1>
</body>
'JavaScript' 카테고리의 다른 글
자바스크립트 - 02.함수(내부함수, 콜백, 클로저, setTimeout과 setInterval ) (0) | 2016.07.11 |
---|---|
자바스크립트 - 01.기본(자료형, 타입, 반복문, 함수) (0) | 2016.07.08 |