繁体   English   中英

在Javascript中使构造函数与它创建的对象具有相同的名称是一个好习惯吗?

[英]Is it a good practice in Javascript to have constructor function having the same name as the object it creates?

假设我们有一个代码

function Vector ( x, y ) 
{
    this.x = x 
    this.y = y
}

var Vector = new Vector() 

一般来说,对象Vector与其构造函数具有相同的名称是否可以?

使用与instanciable函数相同的名称并不是一个好习惯,因为

  • 这很令人困惑,因为你将变量的类型从instanciable更改为instance,
  • 它违反了用小写字母命名实例的良好做法,
  • 它使可实现的功能无法访问。

为了防止混淆,您可以将IIFE作为构造函数。

 var vector = new function (x, y) { this.x = x this.y = y }; console.log(vector); 

您的实例会影响构造函数。 换句话说,你再也不能,除非你试图通过做创建实例后访问的构造函数constructor你的Vector实例。

function Vector ( x, y ) 
{
    this.x = x 
    this.y = y
}

var Vector = new Vector() 

var AnotherVector = new Vector();   // <-Error here 

以上都导致了混乱和缺乏标准的JS实践。

不 - 不要这样做。

为单个实例定义一个类听起来毫无用处。 一个类应该作为模板来创建相同类型的多个实例。 如果你想要第二个载体,你会怎么做?

Vector = function (x, y) {
  this.x = x;
  this.y = y;
};

Vector = new Vector(1, 2); // ok
Vector = new Vector(4, 3); // error

此外,类通常是您为所有实例定义公共API (一组通用方法)的地方。

Vector = function (x, y) {
  this.x = x;
  this.y = y;
};

// Note that in old fashioned JavaScript
// you have to define inherited methods
// in a special object called `prototype`.

Vector.prototype.add = function (vector) {
  this.x += vector.x;
  this.y += vector.y;
};

Vector = new Vector(1, 1);

对于单个实例,您实际上不需要此功能。 在这里使用类是过度的,你可以简单地编写以下代码:

Vector = {
  x: 1,
  y: 1,
  add: function (vector) {
    this.x += vector.x;
    this.y += vector.y;
  }
};

因此,我会说用一个实例覆盖一个类不是一个好习惯,除非这个模式有一些我从未听说过的有用的应用程序:-)

无论如何,这是在JavaScript中使用类的推荐(老式)方式。 如您所见, add方法在Vector类的原型中定义一次,但我们可以从向量ab调用它。

 Vector = function (x, y) { this.x = x; this.y = y; }; Vector.prototype.add = function (vector) { this.x += vector.x; this.y += vector.y; }; Vector.prototype.toString = function () { return "(" + this.x + ", " + this.y + ")"; }; a = new Vector(1, 2); b = new Vector(4, 3); console.log("a = " + a + " b = " + b); a.add(b); console.log("a = " + a + " b = " + b); b.add(a); console.log("a = " + a + " b = " + b); 

不,这不是一个好习惯。

由于JavaScript区分大小写,因此请考虑在变量名中使用全部小写字母。 这可以确保您不会因为滥用大写和小写字母而遇到错误,而且在打字手指上也更容易。

克服这个问题的两个标准惯例是将每个单词大写并将它们塞入(例如,LastName)或用下划线(例如,last_name)分隔每个单词。

好的做法:

 function Vector ( x, y ) { this.x = x ; this.y = y; } var vector = new Vector(1, 2); console.log(vector); 

矢量将不再是一个功能,所以不。 你肯定不想这样做。

检查一下

 function Vector ( x, y ) { this.x = x this.y = y } var Vector = new Vector() var Vector2 = new Vector() 

如果调用您的对象相同的名称,但从小写字母开始更好

由于对象是实例,我会称它们不同。 这取决于你的用例,所以如果知道你只有一个实例,那么你就可以做到。 但是想象有多个实例,那么就可以将它们称为不同的实例。 因此,例如,您有一个具有高xy值的对象:

var highVector = new Vector(1000, 1000) 

您仍在使用单词Vector但现在您知道这是什么类型的Vector

低值的对象可以称为lowVector ,依此类推。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM