我试图更好地理解 JavaScript 中的函数和模块,特别是为了理解创建自己的数据类型的最佳方式。我在下面列出了 2 个文件,Rectangle1.js 和 Rectangle2.js,以及它们的示例输出,我创建这些文件是为了更好地理解这一点。
我希望社区帮助我了解哪些(或其他方式)是构建我的代码以创建我自己的数据类型的最佳方式。
矩形1.js
function Rectangle(x,y,w,h) {
width = w;
height = h;
this.area1 = function() {
return width*height;
}
}
Rectangle.prototype.area2 = function() {
return width * height;
};
Rectangle.area3 = function() {
return width * height;
}
exports.Rectangle = Rectangle;
矩形2.js
var RECTANGLE = (function(my) {
function init(x,y,w,h) {
this.w = w;
this.h = h;
}
function area() {
return this.w * this.h;
}
my.init = init;
my.area = area;
return my;
})(RECTANGLE || {});
exports.RECTANGLE = RECTANGLE;
示例交互
var r2 = require('Rectangle2.js');
r2.RECTANGLE.init(1,2,3,4);
r2.RECTANGLE // ...can see the private properties
r2.RECTANGLE.area() // returns 12
var r1 = require('Rectangle1.js');
r1 // shows area3 in r1
var rect = new r1.Rectangle(1,2,3,4);
rect // shows area1 in rect
rect.area1() // visible in methods, spits out 12
rect.area2() // not visible in methods, spits out 12
r1.Rectangle.area3() // not visible in rect, spits out 12