지오 로케이션은 페이지에서 현재 디바이스(pc나 스마트폰 등)의 위치를 알아내는 방법이다.


값은 위도와 경도 값으로 반환된다.



navigator.geolocation.getCurrentPosition(function(position) {

사용할 위치 관련 내용

});


예를 통해 position키워드를 어떻게 쓰는지 알아보자



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>지오 로케이션</h1>
	<h5>현재 위치 가져오기</h5>
	<p>getCurrentPosition()을 호출하여 사용자의 현재 위치를 가져온다.<br>
	응답은 빠르지만 정확도는 낮다.</p>
	
	<button onclick="test1();">실행확인</button>
	<script type="text/javascript">
		function test1() {
			navigator.geolocation.getCurrentPosition(function(position) {
				alert("위도 : " + position.coords.latitude + "\n" + "경도 : " + position.coords.longitude);
				
				var lat = position.coords.latitude;
				var lon = position.coords.longitude;
				
				// 다음 지도와 연결되고 위치정보를 전달하여 현재 위치를 지도에 띄운다.
				// 정확도가 떨어진다.
				location.href="http://map.daum.net/link/map/나의위치," + lat + "," + lon;
			});
			
		}
	</script>
</body>
</html>


캡슐화는 객체의 요소들을 숨기는 기능으로


getter와 setter로 값을 불러온다.


또한 js에서 상속하는 방법은


this.base 참조를 통해서 본인에게 다른 클래스를 상속하는 방법을


다음 예제로 확인해보자


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	.area{
		height: 150px;
		background: lightgray;
		border: 1px solid black;
	}
</style>
</head>
<body>
	<h1>캡슐화와 상속</h1>
	<h3>캡슐화</h3>
	<button onclick="test1();">실행확인</button>
	<div id="area1" class="area"></div>
	
	<script type="text/javascript">
		function GirlGroup(gn, mc, m) {
			// 속성 초기화
			var groupName = gn;
			var memberCount = mc;
			var members = m;
			
			// setter getter
			this.getGroupName = function() {
				return groupName;
			}
			this.getMemberCount = function() {
				return memberCount;
			}
			this.getMembers = function() {
				return members;
			}
			
			this.setGroupName = function(gn) {
				this.groupName = gn;
			}
			this.setMemberCount = function(mc) {
				if(members.length != mc){
					throw "멤버 수가 틀립니다. 다시 확인하세요!";
				}else {
					memberCount = mc;
				}
			}
			this.setMembers = function(m) {
				this.members = m;
			}
			
		}
		
		function test1() {
			var gn = "소녀시대";
			var mc = 9;
			var m = ["윤아", "써니", "태연", "서현", "티파니", "효연", "유리", "제시카", "수영"];
			
			var girlsGeneration = new GirlGroup(gn, mc, m);
			
			console.log(girlsGeneration);
			
			console.log(girlsGeneration.groupName);
			
			girlsGeneration.groupName = "방탄소년단";
			
			console.log(girlsGeneration.groupName);
			
			console.log(girlsGeneration.getGroupName());
			
			//girlsGeneration.setMemberCount(8);
			
			var area1 = document.getElementById("area1");
			
			with(girlsGeneration){
				area1.innerHTML += "그룹 : " + getGroupName() + "<br>";
				area1.innerHTML += "멤버수 : " + getMemberCount() + "<br>";
				area1.innerHTML += "멤버 : " + getMembers() + "<br>";
			}
		}
	</script>
	
	<hr>
	
	<h3>상속</h3>
	<button onclick="test2();">실행확인</button>
	<script type="text/javascript">
		function Book(t, p, dr) {
			var title = t;
			var price = p;
			var discountRate = dr;
			
			this.getTitle = function() {
				return title;
			}
			this.getPrice = function() {
				return price;
			}
			this.getDiscountRate = function() {
				return discountRate;
			}
			
			this.setTitle = function(t) {
				title = t;
			}
			this.setPrice = function(p) {
				if (p < 0) {
					throw "가격이 어떻게 마이너스냐? 사면 돈주냐?";
				}else {
					price = p;
				}
			}
			this.setDiscountRate = function(dr) {
				if (t < 0) {
					throw "할인율이 마이너스면 말이 되냐?";
				} else {
					discountRate = dr;
				}
			}
		}
		
		// 객체들이 공유하는 prototype에 판매 가격을 구하는 메소드 추가
		Book.prototype.getSellPrice = function() {
			return this.getPrice() - (this.getPrice() * this.getDiscountRate());
		}
		
		function test2() {
			var book1 = new Book('자바의 정석', 35000, 0.15);
			
			alert("title : " + book1.getTitle() + "\n"
					+ "sellPrice : " + book1.getSellPrice())
		}
	</script>
	
	<br>
	
	<button onclick="test3();">상속 확인</button>
	<div id="area2" class="area"></div>
	<script type="text/javascript">
		function Novel(t, p, dr, tp) {
			this.base = Book;
			this.base(t, p, dr);
			// Book을 상속, 생성자 전달
			var type = tp;
			
			this.getType = function() {
				return type;
			}
			this.setType = function(tp) {
				type = tp;
			}
		}
		
		Novel.prototype = Book.prototype;
		
		function test3() {
			var novel = new Novel("나무", 30000, 0.2, '소설');
			
			alert("title : " + novel.getTitle() + "\n"
					+ "sellPrice : " + novel.getSellPrice());
			
			var area2 = document.getElementById("area2");
			
			area2.innerHTML += "novel instanceof Novel : " + (novel instanceof Novel) + "<br>";
			area2.innerHTML += "novel instanceof Book : " + (novel instanceof Book) + "<br>";
			
			console.log(novel);
		}
	</script>
	
	
</body>
</html>


instanceof는 과거 java에서 다형성에서 객체의 관계를 구분할 때 사용 했는데


JS역시 같은 방식으로 사용한다.


그리고 new를 통해서 객체를 생성했을 때와 { }괄호를 사용 했을 때는 차이가 있는데


new를 사용하면 클래스를 지역변수로 생성하고


{ }괄호를 사용하면 window에 전역변수로 생성된다.



<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	.area{
		height: 100px;
		background: lightgray;
		border: 1px solid black;
	}
</style>
</head>
<body>
	<h1>객체 관련 키워드</h1>
	<h3>instanceof 키워드</h3>
	<p>해당 객체가 어떠한 생성자 함수를 통해 생성되었는지 확인할 때 쓴다.</p>
	<button onclick="test1();">실행 확인</button>
	<div id="area1" class="area"></div>
	
	<script type="text/javascript">
		function Dog(name) {
			this.name = name;
		}
		function test1() {
			var myDog = new Dog('까미');
			
			var yourDog = {name:'까미'};
			
			var area1 = document.getElementById("area1");
			
			area1.innerHTML += "myDog instanceof Dog : " + (myDog instanceof Dog) + "<br>";
			area1.innerHTML += "yourDog instanceof Dog : " + (yourDog instanceof Dog) + "<br>";
		}
	</script>
	
	<hr>
	
	<h3>new 키워드</h3>
	
	<button onclick="test2();">new 확인하기</button>
	<div id="area2" class="area"></div>
	<script type="text/javascript">
		function Duck(firstName, lastName) {
			this.firstName = firstName;
			this.lastName = lastName;
		}
		function test2() {
			var duck1 = new Duck("Mc", "Donald");
			console.log(duck1);
			
			var area2 = document.getElementById("area2");
			
			area2.innerHTML += "첫 번째 오리의 full Name은 " + duck1.firstName + duck1.lastName + "입니다. 꽥꽥! <br>";
			
			var duck2 = Duck("Donald", "Dorump");
			
			
			
			//area2.innerHTML += "두 번째 오리의 full Name은 " + duck2.firstName + duck2.lastName + "입니다. 꽥꽥! <br>"; 
		
			console.log(duck2);
			
			area2.innerHTML += "두 번째 오리의 full Name은 " + window.firstName + this.lastName + "입니다. 꽥꽥! <br>"; 
			
			// 두번째 오리의 주석처리된 출력문을 왜 못찾냐 하면
			// new를 붙여 생성하지 않고 생성자를 통해 생성하면 전역변수로 생성된다.
			// new로 호출하면 Duck의 this는 클래스 내부를 의미하고
			// 호출하지 않으면 window를 가리키는 this가 된다.
		}
	</script>
</body>
</html>


+ Recent posts