1 回答

TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
由于Greetr
構(gòu)造函數(shù)調(diào)用Greetr.init
構(gòu)造函數(shù),并通過顯式返回對象來覆蓋其返回值,因此它們之間沒有區(qū)別。
這兩段代碼創(chuàng)建完全相同的對象結(jié)構(gòu)并以相同的方式工作,但有一點不同:第二段代碼保持Greetr.prototype
其初始狀態(tài)。
然而,最有可能的是,原始代碼對同一個對象進(jìn)行了創(chuàng)建Greetr.prototype
,Greetr.init.prototype
因為這樣就可以在不輸入 的情況下訪問和/或擴(kuò)展它.init
,這更具語義性:您打算更改由 所創(chuàng)建的對象的原型Greetr
,其原型通常是Greetr.prototype
。另外,在第一個代碼中,instanceof
將把由Greetr
和創(chuàng)建的對象視為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>
添加回答
舉報