ECMAScript 6 class destructor

前端 未结 5 1140
离开以前
离开以前 2020-12-02 16:23

I know ECMAScript 6 has constructors but is there such a thing as destructors for ECMAScript 6?

For example if I register some of my object\'s methods as event liste

5条回答
  •  离开以前
    2020-12-02 17:05

    "A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."

    Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.

    For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.

    // Set event listeners, hanging onto the returned listener removal functions
    function initialize() {
        $scope.listenerCleanup = [];
        $scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
        $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
        $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
    }
    
    // Remove event listeners when the controller is destroyed
    function onDestroy(){
        $scope.listenerCleanup.forEach( remove => remove() );
    }
    
    
    

提交回复
热议问题