Good evening everyone! Tell me please is there any possibility to make a global variable inside the functions of the ES6 class? For example, pass $ scope and $ http to all the functions that are inside the class. That is, to actually get rid of this. $ Scope = $ scope and this. $ Http = $ http, etc. That in each function there was a variable $ scope and $ http without this.

import {AngularController} from '../core/AngularController'; class XCustomPageController extends AngularController { static $inject = ['$scope','$http']; constructor($scope, $http) { super($scope) $scope.name = "Input new name and click `Set` button" } setNewNameButtonClick(event) { this.$scope.name = event.target.value; } } export default {XCustomPageController}; 
  • are we talking about javascript, not typescript? In any case - as long as it can not be done. Access to the class fields only through this , or super . - Grundy

1 answer 1

While this is not possible.


Access to the class fields only through this , or super . Therefore, if parameters are saved in class fields, they will only be accessed using this .

However, if the provided class is used as a singleton , parameters can be saved to external variables:

 import {AngularController} from '../core/AngularController'; var $scope, $http; class XCustomPageController extends AngularController { static $inject = ['$scope','$http']; constructor(scope, http) { super(scope) $scope = scope; $http = http; $scope.name = "Input new name and click `Set` button" } setNewNameButtonClick(event) { $scope.name = event.target.value; } } export default {XCustomPageController}; 

But it will work correctly only if no more than one instance is created.

  • Here is an idea with external variables that looks very good as a solution, I just got a project where some strange person wrote this in each controller. $ Scope = $ scope ... And AngularController essentially examines all the functions of the class and transfers them to $ scope .. . $ scope [funcName] = func; which is essentially a very clumsy version ... I want a simple and beautiful solution ... - Eugene X