Difference between this vs $scope is clearly answered in this question. One of the projects I am working in, Our senior guy is promoting this
over $scope
arguing it provides better performance.
I tried to find any evidence for the same but official angular documents do have very limited information on this matter.
Can any one please explain
this
provide better performance over $scope
(provided I don't use $watch
etc)$scope
to this
?"How does this and $scope work in AngularJS controllers?" When the controller constructor function is called, this is the controller. When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on.
In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name. Save this answer.
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
AngularJS performance is affected by the number of binding the currently loaded view (page) is using and the watches that you setup manually using $watch
.
All this binding only work on properties declared on $scope.
This means if you are not binding a property to view or not watching it, you better not declare it on the $scope (also called avoiding scope pollution).
Coming to this
, as explained in the SO post this
has different context when invoked by Angular (such as in case of ng-click) and when controller is created.
So anything that you declare on this
(when referring to controller) technically cannot be bound to the view as it is not declared on the scope.
But Angular came up with a controller as
syntax where it allow us to use properties and method over the controller object. In such scenario properties declared over controller are bound in the view using ctrl.prop
syntax.
Internally Angular does something like this when you do ng-controller='HomeController as ctrl'
$scope.ctrl=this
Which basically means Angular is attaching the complete controller object to the $scope
and hence binding with controller properties work.
So only thing that matter in terms of performance is the number of binding being watched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With