After learning about getters and setters, I came across an example that clarified things for me:
var person = {
firstName: 'Jimmy',
lastName: 'Smith'
};
Object.defineProperty(person, 'fullName', {
get: function() {
return firstName + ' ' + lastName;
},
set: function(name) {
var words = name.split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
});
This code is equivalent to:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
}
person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin
The question arises when we see:
person.fullName = 'Jack Franklin';
How does the equal sign trigger the setter method?
2.
Looking at this snippet from an Angular program:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
When we declare or call functions with parameters in Angular like:
function ($scope, $http) {...}
Is there a hidden getter mechanism at play behind the scenes in how those services are injected into the function?