There is an error in the tutorial provided by the author. In CoffeeScript, using @
will always compile to this
in JavaScript. When followed by an identifier such as @restauranteur
, it translates to this.restauranteur
.
While this approach makes sense within a class or a function bound to an object (like a method), it becomes problematic when used in the top scope of a file, as demonstrated in the example. This results in unnecessary and potentially harmful code generation. For instance:
@restauranteur.controller 'HomeCtrl', ['$scope', ($scope) ->
# The body of this controller is empty
]
The above snippet compiles to:
(function() {
this.restauranteur.controller('HomeCtrl', ['$scope', function($scope) {}]);
}).call(this);
In general, referencing this
outside a specific context binds it to the global scope, which can lead to unintended consequences. Therefore, using @
in scenarios not related to class definitions should be avoided.
To prevent namespace pollution, it's recommended to define modules more thoughtfully. Instead of setting up @restauranteur
globally, consider encapsulating it within local scopes:
Main.js.coffee
restauranteur = angular.module('restauranteur', [])
restauranteur.config(['$routeProvider', ($routeProvider) ->
[...]
By reorganizing the code in this manner, potential conflicts with other scripts can be minimized. Moreover, assigning unnecessary variables like restauranteur
should be avoided for clarity reasons.
HomeCtrl.js.coffee
angular.module('restauranteur').controller 'HomeCtrl', ['$scope', ($scope) ->
# The body of this controller is empty
]
However, there are situations where using @
proves beneficial:
describe Restaurant do
before do
@restaurant = Restaurant.new(name: "Momofuku")
end
[...]
In contexts like these, where @
ensures consistency and accessibility within test suites, its usage can streamline coding practices. For instance:
describe "when name is not present" do
before { @restaurant.name = " " }
it { should_not be_valid }
end
When utilized correctly, @
allows for cleaner and more efficient code organization. Understanding its nuances and applications is crucial for maximizing its benefits.