LoginSignup
0
0

More than 5 years have passed since last update.

생성자 함수 "new"

Posted at

생성자 함수는 기술적으로 정규 함수입니다. 그래도 두 가지 규칙이 있습니다.

1.이름은 대문자로 시작합니다.
2.그들은 단지 "new"운영자 와 함께 실행되어야합니다 .

file.js
function User(name) {
    this.name = name;
    this.isAdmin = false;
};

let user = new User("Jack");
alert(user.name); // Jack
alert(user.isAdmin); //false

new User(...)다음과 같이됩니다.

file.js
function User(name){
    //this = {};

    // add properties to this
    this.name = name;
    this.isAdmin = false
}

//new User("Jack")는 다음과 같은 객체이다
let user = {
    name: "Jack",
    isAdmin = flase
}

우리가 다른 사용자를 만들려면 이제, 우리는 호출 할 수 있습니다 new User("Ann"), new User("Alice")등등합니다. 매번 리터럴을 사용하는 것보다 훨씬 짧고 읽기 쉽습니다.

재사용 가능한 객체 생성 코드를 구현하는 것이 생성자의 주요 목적입니다.

기술적으로 모든 함수를 생성자로 사용할 수 있습니다. 즉 : 모든 함수를 실행할 수 있으며 new위의 알고리즘을 실행합니다. "대문자 우선"은 기능이 실행되어야 함을 명확히하기위한 일반적인 합의입니다.

file.js
function User(name){
    //this = {};

    // add properties to this
    this.name = name;
    this.isAdmin = false
}

//new User("Jack")는 다음과 같은 객체이다
let user = {
    name: "Jack",
    isAdmin = flase
}


function BigUser() {
    this.name = "Johin";
    return {
        name: "Godzilla"
    }
}

alert(new BigUser().name);

function smallUser() {
    this.name = "John";
    return;
}
alert(new smallUser().name); //John

괄호생략
인수가 없는경우 괄호를 생략할수 있다

file.js
let user = new User; // <-- no parentheses
// same as
let user = new User();

괄호를 생략하는 것은 "좋은 스타일"로 간주되지 않지만 구문에 의해 허용됩니다.

생성자의 method

file.js
function User(name) {
    this.name = name;
    this.sayHi = function() {
        alert("My name is :"+this.name);
    }
}

let john = new User("John");
John.sayHi();

/*
john = {
    name:"John",
    sayHi: function() {
        alert("My name is":+this.name);
    }
}
file.js
let obj = {};
function A() {
    return obj;
}

function B() {
    return obj;
}

let a = new A();
let b = new B();

alert(a == b
file.js

function A() {

}

function B() {

}

let a = new A();
let b = new B();

alert(a == b
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0