Nice programing

프로토 타입과 클로저가있는 객체 지향 자바 스크립트

nicepro 2020. 11. 28. 12:25
반응형

프로토 타입과 클로저가있는 객체 지향 자바 스크립트


다음 OOP 자바 스크립트 기술의 차이점이 궁금합니다. 그들은 같은 일을하는 것처럼 보이지만 하나가 다른 것보다 더 나은 것으로 간주됩니까?

function Book(title) {
    this.title = title;
}

Book.prototype.getTitle = function () {
    return this.title;
};

var myBook = new Book('War and Peace');
alert(myBook.getTitle())

vs

function Book(title) {
    var book = {
        title: title
    };
    book.getTitle = function () {
        return this.title;
    };
    return book;
}

var myBook = Book('War and Peace');
alert(myBook.getTitle())

두 번째는 실제로 인스턴스를 생성하지 않고 단순히 객체를 반환합니다. 즉, .NET과 같은 연산자를 이용할 수 없습니다 instanceof. 예 : 첫 번째 경우 if (myBook instanceof Book)에는 변수가 Book 유형인지 확인할 수 있지만 두 번째 예제에서는 실패합니다.

생성자에서 객체 메소드를 지정하려면 다음과 같은 적절한 방법이 있습니다.

function Book(title) {
    this.title = title;

    this.getTitle = function () {
        return this.title;
    };
}

var myBook = new Book('War and Peace');
alert(myBook.getTitle())

이 예에서는 둘 다 똑같은 방식으로 작동하지만 차이점이 있습니다. 클로저 기반 구현을 사용하면 개인 변수와 메서드를 가질 수 있습니다 ( this객체에 노출하지 마십시오 ). 따라서 다음과 같은 작업을 수행 할 수 있습니다.

function Book(title) {
    var title_;

    this.getTitle = function() {
        return title_;
    };

    this.setTitle = function(title) {
        title_ = title;
    };

    // should use the setter in case it does something else than just assign
    this.setTitle(title);
}

Book 함수 외부의 코드는 멤버 변수에 직접 액세스 할 수 없으며 접근자를 사용해야합니다.

다른 큰 차이점은 성능입니다. 프로토 타입 기반 분류는 일반적으로 클로저 사용에 포함 된 오버 헤드로 인해 훨씬 ​​빠릅니다. 이 기사에서 성능 차이에 대해 읽을 수 있습니다. http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspx


어떤 것이 더 나은지 는 때때로 그들의 사용 상황에 의해 정의 될 수 있습니다.

프로토 타입클로저 코딩 방법 중 선택하는 방법에 대한 세 가지 제약 사항 (둘 다 적극적으로 사용) :

  1. 성능 / 자원
  2. 압축 요구 사항
  3. 프로젝트 관리

1. 성능 / 자원

개체의 단일 인스턴스의 경우 두 방법 모두 괜찮습니다. 속도 이점은 거의 무시할 수 있습니다.

책 라이브러리를 만드는 것과 같이 100,000 개를 인스턴스화하는 경우 프로토 타입 메서드 가 선호됩니다. 모든 .prototype. 함수는 Closure Method를 사용하는 경우 100,000 번 생성되는 대신 한 번만 생성 됩니다. 자원은 무한하지 않습니다.

2. 압축

사용 폐쇄 방법 if compression efficiency is important (ex: most browser libraries/modules). See below for explanation:

압축-프로토 타입 방법

function Book(title) {
    this.title = title;
}

Book.prototype.getTitle = function () {
  return this.title;
};

YUI가

function Book(a){this.title=a}Book.prototype.getTitle=function(){return this.title};

약 18 % 절약 (모든 공간 / 탭 / 반환). 이 메서드는 모든 프로토 타입 함수가 액세스 할 수 있도록 변수 / 함수를 노출 (this.variable = value)해야합니다. 따라서 이러한 변수 / 함수는 압축에서 최적화 할 수 없습니다.

압축-폐쇄 방법

function Book(title) {
  var title = title; // use var instead of this.title to make this a local variable

this.getTitle = function () {
  return title;
};
}

YUI가

function Book(a){var a=a;this.getTitle=function(){return a}};

약 33 % 절감. 지역 변수를 최적화 할 수 있습니다. 많은 지원 기능이있는 대형 모듈에서는 압축을 크게 줄일 수 있습니다.

3. 프로젝트 관리

In a project with multiple developers, who could be working on the same module, I prefer the Prototype Method for that module, if not constrained by performance or compression.

For browser development, I can override the producton.prototype.aFunction from "production.js" in my own "test.js" (read in afterwords) for the purpose of testing or development, without having to modify the "production.js", which may be in active development by a different developer.

I'm not a big fan of complex GIT repository checkout/branch/merge/conflict flow. I prefer simple.

Also, the ability to redefine or "hijack" a module's function by a testbench can be beneficial, but too complicated to address here...


The former method is how JavaScript was intended to be used. The latter is the more modern technique, popularised in part by Douglas Crockford. This technique is much more flexible.

You could also do:

function Book(title) {
    return {
        getTitle: function () {
            return title;
        }
    }
}

The returned object would just have an accessor called getTitle, which would return the argument, held in closure.

Crockford has a good page on Private Members in JavaScript - definitely worth a read to see the different options.


It's also a little bit about re-usability under the hood. In the first example with the Function.prototype property usage all the instances of the Book function-object will share the same copy of the getTitle method. While the second snippet will make the Book function execution create and keep in the heap 'bookshelf' different copies of the local closurable book object.

function Book(title) {
    var book = {
        title: title
    };
    book.getTitle = function () {
        return this.title += '#';
    };
    return book;
}

var myBook = Book('War and Peace');
var myAnotherBook = Book('Anna Karenina');
alert(myBook.getTitle()); // War and Peace#
alert(myBook.getTitle()); // War and Peace##
alert(myAnotherBook.getTitle()); // Anna Karenina#
alert(myBook.getTitle());// War and Peace###

The prototype members exist in the only copy for all the new instances of the object on the other hand. So this is one more subtle difference between them that is not very obvious from the first sigh due to the closure trick.


here is an article about this in general Book inharets from Book.prototype. In first example you add function to getTitle Book.prototype

참고URL : https://stackoverflow.com/questions/3564238/object-oriented-javascript-with-prototypes-vs-closures

반응형