객체(Object)

Gunwoo Kim·2021년 5월 13일
0

JavaScript

목록 보기
6/17
post-thumbnail

객체(Object)란?

: 자바스크립트는 객체(object) 기반의 스크립트 언어이며 자바스크립트를 이루고 있는 거의 “모든 것”이 객체이다.

객체의 생성

: 자바스크립트에서 객체를 생성하는 방법

  • 리터럴 표기(literal notation)를 이용한 방법

var foo = {
	name : 'foo', // 프로퍼티
	age : 30,
	gender: 'male',
	func1: function () {
		console.log('Hello World')
	}
}

/*
* property 이름은 중복될 수 없다.
* property이름과 property값 사이에 `:` (콜론)으로 구분한다.
* property를 추가할 때는 `,` (쉼표)를 붙여준다.
* property 값에는 어느 type이나 가능하다(string, number, array, object, function..)
*/
  • 생성자 함수(constructor function)를 이용한 방법
// Person() 생성자 함수
var Person = functino(name) {
		this.name = name;
}

// foo 객체 생성
 var foo = new Person('foo');
console.log(foo.name) // foo
  • Object.create() 메소드를 이용한 방법
//Object()를 이용해서 foo 빈 객체 생성
var foo = new Object();

// foo 객체 프로퍼티 생성 
foo.name = 'foo';
foo.age = 30;
foo.gender = 'male';

console.log(typepf foo); // (출력값) object
console.log(foo); // (출력값) { name: 'foo', age: 30, gender: 'male' }

객체 표기법

let plan1 = {   
  name: "Basic"
};
console.log(plan1.name);
console.log(plan1["name"]);

: 아래는 리터럴 표기(literal notation)를 이용한 방법으로 생성한 객체이다.

var person = {
  name: ['Bob', 'Smith'], // 프로퍼티
  age: 32,
  gender: 'male',
  interests: ['music', 'skiing'],
  // 메서드(method)
  bio: function() {
    alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
  },
  greeting: function() {
    alert('Hi! I\'m ' + this.name[0] + '.');
  }
};
  • 점 표기법
// 점표기법 
person.age
person.interests[1]
person.bio()

// 점표기법 
person.age
person.name.first
  • 괄호 표기법
// 괄효 표기법
person['age']
person['name']['first']

메서드(Method)

: 객체에 저장된 값이 함수일 때, 메서드라고 부릅니다.

0개의 댓글