1 回答
TA貢獻1830條經驗 獲得超9個贊
由于Greetr構造函數調用Greetr.init構造函數,并通過顯式返回對象來覆蓋其返回值,因此它們之間沒有區別。
這兩段代碼創建完全相同的對象結構并以相同的方式工作,但有一點不同:第二段代碼保持Greetr.prototype其初始狀態。
然而,最有可能的是,原始代碼對同一個對象進行了創建Greetr.prototype,Greetr.init.prototype因為這樣就可以在不輸入 的情況下訪問和/或擴展它.init,這更具語義性:您打算更改由 所創建的對象的原型Greetr,其原型通常是Greetr.prototype。另外,在第一個代碼中,instanceof將把由Greetr和創建的對象視為Greetr.init的實例Greetr。所以:
(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 instanceof G$);
<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 instanceof G$);
<html>
<head>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>
添加回答
舉報
