문제

I have a class which has been instantiated many times and I would like to change a certain instance variable for all of them. How would I go about doing this using dat.js?

e.g

function MyClass(){
   this.x = 1;
}
var arr = [];

for(var i =0; i< 10; i++){
   arr.push(new MyClass());
}

How can I alter the x variable for all instances of MyClass.

도움이 되었습니까?

해결책

The only way that I can think of to alter the instance variables without making any changes to MyClass would be to iterate over arr.

Alternatively, if you really mean for all instances to share a common property, maybe what you want to do is use something similar to a static variable in classical programming. These can be accomplished by taking advantage of the fact that functions are really just objects in JavaScript, so you can add a property to the function constructor: MyClass.x = 1;. When you want to change all instances' x value, you can update them at once just by changing MyClass.x = 2;. This technique alters the way you access the variable, so instead of this.x you'll need to reference it by MyClass.x.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top