1

我试图更好地理解 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
4

1 回答 1

1

在 javascript 中构造对象的首选方式更接近于您在 Rectangle1.js 中编写的方式,尽管存在一些问题:

首先,在Rectangle(x,y,w,h)构造函数中接受参数时,您不是将它们分配给实例变量,而是分配给一个有点不安全的全局范围,这解释了为什么Rectangle.area3()返回相同的结果。this关键字允许您分配和访问实例变量。保持其他一切相同,您宁愿需要像这样定义构造函数(注意使用this.):

function Rectangle(x,y,w,h) {

  this.width = w;
  this.height = h;

  this.area1 = function() {
    return this.width*this.height;
  }
}

Rectangle.prototype.area2 = function() {
  return this.width * this.height;
};

此外,理想情况下,当您定义将在同一对象的所有实例中以相同方式重用的函数时,最好将它们定义为 onRectangle.prototype而不是this在构造函数中定义。在第一种情况下,只创建一个 Function 对象并为Rectangle;的所有实例共享。在后者中,为每个Rectangle.

构建模块的方式很好,因为您的目标是一个 javascript 平台,您可以在其中组织类似 CommonJS 的模块中的代码,例如 Node.js。

于 2013-01-12T04:55:22.110 回答