[Javascript]함수(2)

이대희·2021년 1월 24일
0
post-thumbnail

객체

let person = {
    name : 'lee',
    introduce : function(){
        return 'My name is '+this.name;
    }
}
console.log(person.name); // lee
console.log(person.introduce); //[function:introduce] 
console.log(person.introduce()); //My name is lee

person객체에 name introduce프로퍼티로 구성되있다. namelee값이 들어있고 introduce에는 함수가 있다.
이 함수를 메소드라고 부르며 person.introduce라고 표기한다.person.introduce()는 함수를 호출하여 실행하는 것이고 person.introduce는 함수자체를 불러오는것으로 위 콘솔에서 함수자체를 받는 것을 확인할 수 있다.

let person = {}
person.name = 'lee';
person.introduce = function(){
    return 'My name is '+this.name;
}

빈 객체를 먼저 선언하고 person.name으로 객체안에 프로퍼티 값을 줄수있다.

new

Case1

function Person(){}
let p1 = new Person();
p1.name = 'lee';
p1.introduce = function(){
    return 'My name is '+this.name; 
}

var p2 = new Person();
p2.name = 'kim';
p2.introduce = function(){
    return 'My name is '+this.name; 
}

person함수에 new를 붙이면 person에 객체 타입으로 생성할 수 있고 이름은 p1이라는 변수에 넣게된다.
p1에는 name프로퍼티에 'lee'라는 값이 들어있고 같은 introduce함수를 리턴한다. 같은 내용의 함수를 두번씩 쓰기에 함수 하나로 선언을 하고 선언된 함수를 재사용하여 효율성을 높인다.

function Person(names){
    this.name = names;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}
let p1 = new Person('lee');
 
let p2 = new Person('kim');

person함수를 this를 이용해 초기화된 함수로 정의한다. 여기서 this는 name을 생성자로 사용한다는 의미다.

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

car에 make, model, yaer 를 this.를 붙여 생성사로 사용하여 재사용성을 높일 수 있다.

let mycar = new Car("Eagle", "Talon TSi", 1993);
let yourscar = new Car("Nissan", "300ZX", 1992);

function으로 틀을 만들고 new로 틀에서 원하는 것을 찍어낸다.

0개의 댓글