프로그래밍/JavaScript

Javascript > window 객체 > 객체 생성하기 > 개념정리

에그티비 2024. 10. 9. 22:17

HTML 문서에서 최상의 객체는 window 이다.

 

html 문서에서

<script>
    var name = 'kim';
    function sayHi () {
        return 'Hello';
    }

    console.log(name);
    console.log(sayHi());
</script>

 

위의 코드는 아래와 같다.

<script>
var name = 'kim';

function sayHi () {
 return 'Hello';
}

window.hi = function () {return 'Hi'};
 
console.log(window.name);
console.log(window.sayHi());
console.log(window.hi());
</script>

순수 JavaScript 문서 JS 파일에서

객체 생성 하기

기본형식

var 학생 = {}

console.log(typeof 학생);

 

변수와 함수 추가하기

var 학생 = {
    name: 'kim',
    sayHi: function () {
        console.log('Hi');
    }
}

 

객체에 함수를 추가하는 방식 표현 2가지

    sayHi: function () {
        console.log('Hi');
    },
    
    sayHi() {
        console.log('Hi');
    }

 

객체 찍어내기

function Student(name) {
    this.name = name;
    this.sayHi = function () {
        console.log('Hi ' + this.name);
    }
}

var 학생1 = new Student('kim');
학생1.sayHi();

var 학생2 = new Student('lee');
학생2.sayHi();

 

객체 기능 추가하기 prototype

객체 생성기에서만 prototype 문법이 가능하다.

function Student(){
    this.name = 'Kim';
    this.age = 15;
  }

  Student.prototype.gender = '남';
  
  Student.prototype.sayHi = function () {
    return 'Hi ' + this.name;   
  }
  
  var 학생1 = new Student();
  console.log(학생1.gender);
  console.log(학생1.sayHi());
  
// __proto__ 는 부모의 prototype 를 가리킨다.
console.log(학생1.__proto__);
console.log(기계.prototype);

 

단순 객체에서는 아래처럼 가능하다.

const Student = {}

Student.sayHi = function() {return 'Hi'}

// 에러발생함.
//Student.prototype.sayHi = function() {return 'Hi'}

console.log(Student.sayHi());

 

객체와 배열

const 학생 = {}
console.log(typeof 학생);
console.log(학생.__proto__);

// __proto__ 는 부모 객체를 알려준다.
if(학생.__proto__ === Object.prototype)
    console.log('같다');


    var 학생1 = new Object();
    var 학생2 = new Object();

    Object.prototype.sayHi = function () {
        return 'Object.prototype.sayHi';
    }

    console.log(학생1.sayHi());
    console.log(학생2.sayHi());


    const 배열 = [1, 2, 3, 4, 5];
    const 배열2 = new Array(1, 2, 3, 4, 5);

    배열.sayHi = function () {
        return '배열.sayHi';
    }

    console.log(배열.sayHi());

    console.log(배열.__proto__);
    console.log(배열2.__proto__);

    console.log(배열.__proto__ === Array.prototype);

    console.log(Array.prototype.__proto__ === Object.prototype);
    console.log(Object.prototype.__proto__ === null);
 
object
[Object: null prototype] {}
같다
Object.prototype.sayHi
Object.prototype.sayHi
배열.sayHi
Object(0) []
Object(0) []
true
true
true

핵심정리

{} [] 는 다음과 같이 문법을 단순화 시킨 형식이다.

const 객체 = new Object()
const 객체 = {}

const 배열 = new Array()
const 배열 = []

 

prototype 은 객체 생성기에서만 가능한 문법이다.