2014-05-19 2 views
0

저는 TS 생성자로 고민하고 있습니다. 나도이 stackoverflow에 게시하십시오.여러 타이프 스크립트 생성자

public Animal(){ 
    this.name = “default”; 
    this.noise =””; 
public Animal(string name){ 
    this.name = name; 
    this.noise = “”; 
} 
public Animal(string name, string noise){ 
    this.name = name; 
    this.noise = noise; 
} 

당신이 타이프에서이 같은 일을 수행

는이 세 가지 생성자에 해당하게하고 싶은 말은?

Constructor(name?:string, noise?:string){ 
    if(name!= null) 
     this.name =name; 
    else 


    this.name = ""; 
     if(string != null) 
      this.noise = noise; 
     else 
      this.noise = ""; 
} 

등등?

int 또는 string으로 동물을 선언 할 수있는 다양한 프리미티브가 있다면 어떻할까요? instanceof를 사용하고 있습니까?

감사합니다. 이 매우 간단하게 수행 할 수 있습니다

답변

2

나단 : 자바 스크립트에없는 매개 변수의 값이 undefined하지 null을 가지고

class Animal { 
    constructor(public name = 'default', public noise = '') { 
    } 
} 

참고 :이 또한 정확히 동일합니다

class Animal { 
    public name: string; 
    public noise: string; 

    constructor(name = 'default', noise = '') { 
     this.name = name; 
     this.noise = noise; 
    } 
} 

.