[JavaScript]コンストラクタ


コンストラクタ


複数の類似オブジェクトを作成する必要がある場合?

function User(name, age){
	this.name = name;
    this.age = age;
} 

let user1 = new User('Mike', 30);
let user2 = new User('Jane', 22);
let user3 = new User('Tom', 17);
  • 関数の最初のアルファベットは大文字です./new演算子呼び出しを使用します.
  • コンストラクション関数の動作


    さぎょうモード

    function User(name, age){
    	this = {} // 생략가능 코드
        
        this.name = name;
        this.age = age;
        
        return this; // 생략가능 코드
    }
    
    new 함수명(); // 실행 함수 

    コンストラクタメソッドの追加

    function User(name, age){
    	this.name = name;
        this.age = age;
        this.sayName = function(){
        	console.log(this.name); // this 는 user5를 가르킨다.
        }
    } 
    
    let user5 = new User('Han', 40);
    user5.sayName(); // 'Han'