I've been grappling with an example from a course titled "JavaScript: Understanding the Weird Parts". In this example, there's a line of code
Greeter.init.prototype = Greeter.prototype;
, which sets Greeter.prototype
as the prototype for all objects created using the Greeter.init
function constructor. This allows us to define methods in Greeter.prototype
.
However, I'm puzzled as to why we can't just set the methods directly in Greeter.init.prototype
. It seems like the line
Greeter.init.prototype = Greeter.prototype;
is unnecessary. What advantage does the original approach offer?
Original code:
(function(global, $) {
var Greetr = function(firstName, lastName, language) {
return new Greetr.init(firstName, lastName, language);
}
Greetr.prototype = {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
Greetr.init = function(firstName, lastName, language) {
var self = this;
self.firstName = firstName || '';
self.lastName = lastName || '';
self.language = language || 'en';
}
Greetr.init.prototype = Greetr.prototype;
global.Greetr = global.G$ = Greetr;
}(window, jQuery));
var g = G$('John', 'Doe');
console.log(g);
console.log(g.fullName());
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>
Simplified code:
(function(global, $) {
var Greetr = function(firstName, lastName, language) {
return new Greetr.init(firstName, lastName, language);
}
Greetr.init = function(firstName, lastName, language) {
var self = this;
self.firstName = firstName || '';
self.lastName = lastName || '';
self.language = language || 'en';
}
Greetr.init.prototype = {
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
global.Greetr = global.G$ = Greetr;
}(window, jQuery));
var g = G$('John', 'Doe');
console.log(g);
console.log(g.fullName());
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>