JavaScript Object

Develop My Life·2020년 4월 29일
0

JavaScript

목록 보기
14/15

Object 객체

  • 영어로는 Object object로 Object 객체를 가리킨다.
  • Object 객체는 모든 객체의 prototype이다.
  • 모든 객체에 상속되는 속성이다.
  • 모든 객체가 공통으로 사용할 수 있다.

Object MDN 문서 읽기

MDN 사이트
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object

Object.메소드() 사용법

이 메소드는 object 객체 안에 있는 함수로 object.메소드() 형태로 사용할 수 있는 것이다.

예시 - object.keys()

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
	var arr = ["a","b","c"]; 
	var o = {'name' : 'dong', 'age' : 23};

	document.write(Object.keys(arr)); //출력 : 0, 1, 2
	document.write(Object.keys(o)); //출력 : name, age
	
</script>
</body>
</html>

Object.prototype.메소드() 사용법

이 메소드는 Object의 prototype 안에 있는 메소드로 모든 object 객체에 상속되기 때문에 생성된 객체.메소드() 형태로 사용할 수 있는 것이다.

예시 - object.prototype.tostring()

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
	var arr = ["a","b","c"]; 
	var o = new Object();
	
	document.write(arr.toString()); //출력 : a, b, c
	document.write(o.toString()); //출력 : [object Object]

</script>
</body>
</html>

object의 prototype을 수정하여 자신이 원하는 기능을 전체 object 객체에 추가할 수 있다.

Object의 prototype 확장

자신이 만들고 싶은 기능을 object.prototype의 속성이 추가해줌으로써 object 객체의 기능을 확장할 수 있다.

예시

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
	Object.prototype.contain = function(neddle) { 
	//Object.prototype에 contain이라는 함수를 추가하여 기능을 추가한다.
    for(var name in this){
        if(this[name] === neddle){
            return true; //객체의 값 중에 있다면 true
        }
    }
    return false; //객체의 값 중에 없다면 false
}

var o = {'name':'dong', 'city':'seoul'}
document.write(o.contain('dong')); //출력 : true
document.write(o.contain('hyeon')); //출력 : false
</script>
</body>
</html>

Object의 prototype 확장 시 주의사항(with hasOwnProperty)

  • Object의 prototype 확장 시 모든 객체에 영향을 주기 때문에 주의해야 한다.

예시

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<script type="text/javascript">
	Object.prototype.contain = function(neddle) { 
	//Object.prototype에 contain이라는 함수를 추가하여 기능을 추가한다.
    for(var name in this){
        if(this[name] === neddle){
            return true; //객체의 값 중에 있다면 true
        }
    }
    return false; //객체의 값 중에 없다면 false
}

var o = {'name':'dong', 'city':'seoul'}

for(name in o){
	document.write(name+" "); //출력 : name city contain
	//확장 전 출력 : name city
	//prototype 확장으로 생성된 모든 객체에 contain이 추가된 것이다.
}

for(name in o){
	if(o.hasOwnProperty(name)){//o 객체 자신이 가지고 있는지 확인할 수 있는 object.prototype의 메소드 true/false
		document.write(name+" "); //출력 : name city
	}
}
</script>
</body>
</html>
  • Object.prototype 확장으로 모든 객체에 contain이라는 것이 추가되어 영향을 미쳤다.
  • 내가 원하지 않는 값이 출력될 수 있다.
  • Object.prototype.hasOwnProperty 를 이용하여 수정 가능하다.

    따라서 Object.prototype을 확장할 때에는 모든 상황을 고려하여 신중하게 기능을 추가해야한다.

0개의 댓글