2011-09-06 55 views
3

具有相同功能的構造函數創建在試圖建立一個對象與該保持與具有相同的構造創建的所有對象的陣列的構造函數一個內禮對象的所有實例。陣列與在Javascript

我想,最好的辦法是與對象初始化一個封閉,這是我嘗試解決這個問題:

 

    function myObject (name){ 
     this.name=name; 
     this.allInstances = []; 
     } 

    myObject.ptototype = { 

     init : function(){ 
      return function(){this.allInstances.push(this.name)}; 
      }(), 
     } 

    object1 = new myObject("object1"); 
    object2 = new myObject("object2"); 
    console.log(object1.allInstances); // should print ["object1", "object2"] 

有誰知道如何做到這一點?這甚至有可能嗎?
我專門試圖讓只使用函數構造函數和原型,以實現一個解決方案。

我知道如何通過推動禮節到外部陣列等來解決:

 

    var allInstances = []; 
    function myObject (name){ 
     this.name=name; 
     allInstances.push(this.name); 
     } 
    console.log(allInstances) 

回答

5

放置陣列作爲屬性上prototype,它將所有實例之間共享:

function myObject(name) { 
    this.name = name; 
    this.allInstances.push(this.name); 
} 

myObject.prototype.allInstances = []; 

object1 = new myObject("object1"); 
object2 = new myObject("object2"); 

console.log(object1.allInstances); // ["object1", "object2"] 

或者,如果你想要的陣列進行更保護,使用模塊模式,包括功能上的原型返回數組。

var myObject = (function() { 
    var allInstances = []; 

    function func(name) { 
     this.name = name; 
     allInstances.push(this.name); 
    } 

    func.prototype.getAllInstances = function() { return allInstances; }; 

    return func; 
})(); 

object1 = new myObject("object1"); 
object2 = new myObject("object2"); 

console.log(object1.getAllInstances()); // ["object1", "object2"] 
+0

萬分感謝!!!!你是個天才! –

1

你可以把你的陣列的myObject靜態成員:

function myObject (name) { 
    this.name=name; 
    this.init(); 
} 
myObject.allInstances = []; 
myObject.prototype = { 
    init: function() { 
     myObject.allInstances.push(this.name); 
    } 
}; 

我不知道你在哪裏打電話init()。我在構造函數中添加了對init()的調用。

1

在我看來,這將是很容易做到,像這樣:

var MyType = function(name) 
{ 
     this.name = name; 
     MyType.Instances.push(this.name); 
}; 

MyType.Instances = []; 

MyType.prototype.getInstances = function() 
{ 
    return MyType.Instances; 
}; 

var obj = new MyType('Hello'); 
var obj2 = new MyType('hello 2'); 

console.log(obj2.getInstances()); 
0

請問這怎麼辦?

function myObject(name) { 
    this.name = name; 
    this.constructor.allInstances.push(this.name); 
} 

myObject.allInstances = []; 

object1 = new myObject("object1"); 
object2 = new myObject("object2"); 
console.log(myObject.allInstances); 
+1

更換'myObject.allInstances.push(this.name);'和'this.constructor.allInstances.push(this.name);'http://jsfiddle.net/7Xnwn/ –

+0

可能是更好的,是的。謝謝。 – ZenMaster