簡體   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