constructor(name) {
this.name = name;
}
sayHi() {
alert(this.name);
}
let user = new User("john");
user.sayHi();
constructor(생성자)를 사용하면 인스턴트화된 객체에서 다른 메서드를 호출하기 전에 수행해야 하는 지정 초기화를 제공할 수 있습니다.
클래스를 new를 붙여서 (new User("John")) 인스턴트 객체로 생성하면 넘겨받은 인수와 함께 constructor가 먼저 샐행됩니다.
이 때 넘겨받은 인수의 John이 this.name에 할당됩니다.
class Car {
constructor(brand) {
this.carname = beand;
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return super.present() + ', it is a' + this.model;
}
}
let mycar = new Model("Ford", "Mustang");
mycar.show();
class Component {
constructor(props) {
this.props = props;
// ...
}
}
class Square exrends React.Component {
constructor(props) {
// can't use `this` yet
super(props);
// now it's okay though
this.state = { a: true };
}
// ...
}
class Person {
constructor(name) {
this.name = name;
}
}
class PolitePerson exrends Person {
constructor(name) {
// this가 위에 있어서 오류코드
this.greetColleagues();
super(name);
}
greetColleagues() {
alert('My name is' + this.name + ', nice to meet you!');
}
}
// Inside React
class Component {
constructor(props) {
this.props = props;
// ...
}
}
// Inside your code
class Button extends React.Component {
constructor(props) {
super(); // we forgot to pass props
console.log(props); // ok {}
console.log(this.props); //undefined
}
// ...
}
class Button extends React.Component {
constructor(props) {
super(props);
console.log(props); // ok {}
console.log(this.props); // ok {}
}
// ...
}