WEB2 - JavaScript 32 (객체프로퍼티와 메소드)

WEB2 - JavaScript 32 (객체프로퍼티와 메소드)

객체프로퍼티와 메소드

객체에는 함수도 담을 수 있다.

ex10.html

만들어둔 coworkers 를 활용하여 coworkers 라는 객체에 메소드를 추가해보자.

showAll 이라는 메소드를 추가

(coworkers 에 있는 각각의 데이터들을 iterate 해서 화면에 출력하는 코드)

coworkers.showAll = function(){ }

이것은 이렇게 정의할 수도 있다.

function showAll(){ }

var showAll = function(){ }

(모두 다 똑같은 표현)

object Create var coworkers = { "beginner":"livebyfaith117", "programmer":"egoing" }; document.write("beginner:"+coworkers.beginner+"
"); document.write("programmer:"+coworkers.programmer+"
"); coworkers.bookkeeper="duru"; document.write("bookkeeper:"+coworkers.bookkeeper+"
"); coworkers["data scientist"]="taeho"; document.write("data scientist:"+coworkers["data scientist"]); Iterate for(var key in coworkers){ document.write(key+':'+coworkers[key]+'
'); } Property & Method coworkers.showAll = function(){ for(var key in coworkers){ document.write(key+':'+coworkers[key]+'
'); } } coworkers.showAll();

이렇게 작성을 하고 나면 좋은 코드 작성이 아니다.

변수 coworkers 가 for 문에 박혀있기 때문에 객체가 바뀐다면 정보를 못 가져오는 현상이 발생할 수 있다.

여기서 this 를 쓰는 것이다.

그렇게 되면 변수 coworkers 가 바뀌어도 this 는 자기 자신을 가리키기 때문에 영향을 받지 않는다.

object Create var coworkers = { "beginner":"livebyfaith117", "programmer":"egoing" }; document.write("beginner:"+coworkers.beginner+"
"); document.write("programmer:"+coworkers.programmer+"
"); coworkers.bookkeeper="duru"; document.write("bookkeeper:"+coworkers.bookkeeper+"
"); coworkers["data scientist"]="taeho"; document.write("data scientist:"+coworkers["data scientist"]); Iterate for(var key in coworkers){ document.write(key+':'+coworkers[key]+'
'); } Property & Method coworkers.showAll = function(){ for(var key in this){ document.write(key+':'+this[key]+'
'); } } coworkers.showAll();

이렇게 화면에 출력된 것을 보면 showAll 이 coworkers 에 소속된 데이터이기 때문에 showAll 도 화면에 표시가 된다.

이런 문제를 없애기 위해서는 for문 안에서 if문으로 'for문을 제외한다' 라는 코딩을 하면 되겠지만 이 시간에는 중요하지 않기 때문에 skip.

객체에 소속된 변수의 값으로 함수를 지정할 수 있고,

coworkers.showAll = function(){ for(var key in this){ document.write(key+':'+this[key]+''); } }

이것으로 인해 객체에 소속된 함수를 만들 수 있었다.

coworkers.showAll();

그리고 객체에 소속된 함수를 메소드(Method) 라고 한다.

객체에 소속된 변수를 가리키는 말을 프로퍼티(Property) 라고 한다.

( ex property = beginner, programmer, bookkeeper, data scientist )

from http://livebyfaith117.tistory.com/33 by ccl(A) rewrite - 2021-09-29 16:01:14