簡體   English   中英

Javascript構造函數來計算實例的數量

[英]Javascript constructor function to count the number of instances

好的,所以我想在 javascript 中創建一個構造函數,它將計算使用此構造函數創建的實例總數。

var Component = function(name) {
    this.name = name;
    this.add = function(){this.prototype.countInstances++;};
    this.add();
};

Component.prototype.countInstances=0;

正如我正確理解的那樣,countInstances 變量被添加到原型中,並將充當所有實例的靜態副本,並將充當我的計數器。

此代碼的問題在於,由於我在構造函數之后聲明了 countInstances,因此在構造函數代碼本身中出現錯誤。 這個怎么改??

如果您希望將屬性附加到類本身,而不是類的實例,則不想將屬性添加到原型:

var Component = function(name) {
  this.name = name;
  Component.instanceCount++;
};

Component.instanceCount = 0;

這樣,您將每個名稱分配給它的實例,並將實例總數分配給靜態類:

var foo = new Component('bar');
var baz = new Component('qux');

console.info(foo.name, baz.name, Component.instanceCount);

>> 'bar', 'qux', 2

正如我正確理解的那樣,countInstances 變量被添加到原型中,並將充當所有實例的靜態副本,並將充當我的計數器。

不,它實際上是實例的默認值,而不是“靜態”。 如果你把它放在Component.prototype ,所有的實例都將通過原型鏈繼承它,但是通過一個實例改變它會給那個實例它自己的副本。 例子:

var Foo = function() {
};
Foo.prototype.bar = 0;
var f1 = new Foo();
var f2 = new Foo();
console.log(f1.bar, f2.bar); // 0, 0 -- both are still using the `bar` on the prototype
++f1.bar;
console.log(f1.bar, f2.bar); // 1, 0 -- f1 now has its own
Foo.prototype.bar += 2;
console.log(f1.bar, f2.bar); // 1, 2 -- f2 is still using the `bar` on the prototype

此代碼的問題在於,由於我在構造函數之后聲明了 countInstances,因此在構造函數代碼本身中出現錯誤。 這個怎么改??

不,問題是你的實例沒有this.prototype對象。 函數的prototype屬性不會被復制為實例的prototype屬性; 它被分配給他們作為他們的原型,這(有點令人困惑)不被稱為prototype 很長一段時間內,它在規范之外根本沒有名稱。 您可以通過Object.getPrototypeOf(this)或(這將是下一個規范中基於瀏覽器的 JavaScript 的標准Object.getPrototypeOf(this)訪問它__proto__屬性。

但是把它放在原型上可能沒有意義。 我只是在函數本身上使用一個屬性:

var Component = function(name) {
    this.name = name;
    this.add = function(){Component.instances++;};
    this.add();
};
Component.instances = 0;

但是你說你想計算構造函數創建的對象的數量; 以上統計了add方法被調用的次數。 要計算構造函數創建的實例數,請在構造函數中增加它:

var Component = function(name) {
    Component.instances++;
    this.name = name;
    this.add = function(){/*Presumably you're doing something here*/};
    this.add();
};
Component.instances = 0;
var ComponentCounter = 0;

var Component = function(name) {
    this.name = name;
    this.add = function(){this.prototype.countInstances++;};
    this.add();
    ComponentCounter++;
    // or Component.counter++;
};

// or add it as a property of Component after it has been defined
// Component.counter = 0;

原型中的變量屬於實例,因此您必須在實例之間持久化的變量上跟蹤該數據。

我們將能夠通過使用:

function component() {
    if(component.prototype.counter) {    component.prototype.counter = 0; }
    component.prototype.counter++;
    this.add = function(){ /*... do something here....*/ }
}

通過在函數體內啟動 counter,我們將能夠保持計數(函數調用的次數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM