我试图理解“JavaScript:理解奇怪的部分”课程中的一个例子。有一行代码Greeter.init.prototype = Greeter.prototype;用于使函数构造函数Greeter.prototype创建的所有对象成为原型Greeter.init,因此我们可以在Greeter.prototype.
但我不明白为什么不直接在Greeter.init.prototype. 效果是一样的。该行Greeter.init.prototype = Greeter.prototype;看起来像是多余的代码。原始方法的优点是什么?
原始代码:
(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>
简化代码:
(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>
慕标琳琳
相关分类