IT

생성자 함수와 프로토 타입에서 자바 스크립트 객체 메소드 선언

lottoking 2020. 6. 16. 07:57
반응형

생성자 함수와 프로토 타입에서 자바 스크립트 객체 메소드 선언 [중복]


이 질문에는 이미 답변이 있습니다.

자바 스크립트 객체를 만들 때 생성자 함수 또는 프로토 타입에 메소드 선언을 넣을 수 있습니다. 예를 들어 Name 속성과 Bark 메서드가있는 Dog 클래스를 원한다고 가정합니다. Bark 메소드 선언을 생성자 함수에 넣을 수 있습니다.

var Dog = function(name) {
    this.Name = name;
    this.Bark = function() {
        alert(this.Name + " bark");
    };
}

또는 프로토 타입 객체에 메소드로 넣을 수 있습니다.

var Dog = function(name) {
    this.Name = name;
}

Dog.prototype.Bark = function() {
    alert(this.Name + " bark");
};

Dog 유형의 객체를 인스턴스화하면 두 가지 접근 방식이 모두 잘 작동하는 것 같습니다.

var dog = new Dog("Fido");
dog.Bark();  //Both approaches show "Fido bark"

이 방법 중 하나를 다른 방법보다 선호해야합니까? 하나를 다른 것보다 사용하면 어떤 이점이 있습니까? 무대 뒤에서이 두 가지 접근 방식이 정확히 같은 일을합니까? 대부분의 사람들이 선호하는 접근 방식은 무엇입니까?

도와 주셔서 감사합니다.


예를 들어, 프로토 타입 접근법을 사용해야합니다. 일반적으로 다릅니다. 첫 번째 접근 방식 (생성자의 메소드 초기화)의 주요 장점은 메소드의 생성자 내에 정의 된 로컬 변수를 사용하여 클로저를 활용할 수 있다는 것입니다. 이러한 변수는 생성자 함수 외부에서 직접 액세스 할 수 없으므로 효과적으로 "비공개"입니다. 즉, 이러한 변수가 객체의 속성으로 정의 된 경우보다 API가 더 깨끗합니다. 일반적인 몇 가지 일반적인 규칙 :

  • 메소드가 생성자에 정의 된 로컬 변수를 사용하지 않는 경우 (예 : 그렇지 않은 경우) 프로토 타입 접근법을 사용하십시오.
  • 을 많이 생성 Dog하는 경우 프로토 타입 접근법을 사용하십시오. 이런 식으로 모든 "인스턴스"(즉, Dog생성자가 생성 한 객체 )는 하나의 함수 집합을 공유하지만 생성자 방식에서는

    Dog생성자가 호출 될 때마다 더 많은 메모리를 사용하여 새로운 함수 집합이 생성됩니다 .
  • 적은 수의을 생성하고 Dog생성자에서 로컬 "비공개"변수를 사용하면 코드가 향상되는 것이 더 나은 방법 일 수 있습니다. 성능 또는 메모리 소비가 주요 관심사 인 경우 판단을 사용하고 벤치 마크를 수행하십시오.

로컬 개인 생성자 변수에 액세스해야하는 메서드 만 생성자에 정의되고 다른 메서드는 프로토 타입에 할당되는 하이브리드 방식을 사용할 수 있습니다.

예를 들어, 아래 코드는 생성자에서 지역 변수를 사용하여 실제 개를 비공개로 유지하면서이 개가 짖는 횟수를 추적하므로 짖는 관련 메소드는 생성자 내부에서 정의됩니다. 테일 흔들림은 수의 껍질에 접근 할 필요가 없으므로 프로토 타입에서 해당 방법을 정의 할 수 있습니다.

var Dog = function(name) {
    this.name = name;

    var barkCount = 0;

    this.bark = function() {
        barkCount++;
        alert(this.name + " bark");
    };

    this.getBarkCount = function() {
        alert(this.name + " has barked " + barkCount + " times");
    };
};

Dog.prototype.wagTail = function() {
    alert(this.name + " wagging tail");
};

var dog = new Dog("Dave");
dog.bark();
dog.bark();
dog.getBarkCount();
dog.wagTail();


첫 번째 것은 프로토 타입 객체 에만 메소드에 대한 참조를 저장 하고 두 번째 솔루션은 객체 에 메소드를 저장 합니다. 이것은 각 객체가 여분의 포인터를 포함하므로 각각 조금 더 많은 메모리를 차지한다는 것을 의미합니다.

The per-object method allows the method to refer to variables in the constructor (a closure) and it therefore allows you to access some data that you cannot access from a prototype methods.

Finally, a prototype method can be changed later, that is you can redefine Bark at runtime on the prototype object, and this change will work for all objects with this prototype (since the method is always looked up through the prototype).


The vast majority of javascript code that I've seen uses the prototype method. I think that there are three reasons for this that I can think of off the top of my head.

The first is that you avoid having every class be a huge constructor: constructor logic goes in the constructor function, logic for other methods is declared elsewhere--this is mostly a clarity thing / separation of concerns thing, but in javascript you need every bit of clarity you can get your hands on.

The second is efficiency. When you declare methods in the constructor, you are creating a new instance of the function object for each instance of the object, and also binding the scope of the constructor to each of these functions (that is, they can reference, for example, the arguments to the constructor, which can then never be gc'd as long as the object lives). When you declare methods on the prototype there is a single copy of the function object that is used by all instances--prototype properties are not copied onto instances.

A third reason is that you can "extend" a class in various ways when you use the prototype method, such as the prototype chaining used by Backbone.js and CoffeeScript's class construct.

참고URL : https://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype

반응형