toString

es버전
Tags
문자열
비고
메소드를 재정의하여 toString() 호출 시 어떻게 반환할 건지 설정 후 사용
기본적으로는 [object Object]가 반환되는데, 메소드 재정의를 통해 수정 가능.
function Dog(name) { this.name = name; } const dog1 = new Dog('Gabby'); Dog.prototype.toString = function dogToString() { return `${this.name}`; }; console.log(dog1.toString()); // expected output: "Gabby"

예시

function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
메소드 재정의 전
theDog.toString(); // returns [object Object]
메소드 재정의 후
Dog.prototype.toString = function dogToString() { var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed; return ret; } // ==> "Dog Gabby is a female chocolate Lab"