2017-10-03 4 views
0

그래서 나는 수 백번 생성 된 객체를 가지고 있으며 프로토 타입을 사용하여 각각을 다른 값으로 모두 업데이트합니다. 그러나 개체의 값을 액세스 할 수 없기 때문에 내가 잘못 개체를 호출 오전 믿습니다. 프로토 타입에서 객체 값을 호출하는 올바른 방법은 무엇입니까?

var asteroids = []; 

//Create some objects 
for (i=0; i<100; i++) { 
    asteroids[i] = new Asteroid(); 
} 

function Asteroid() { 
    this.x = Math.random(); 
    this.y = Math.random(); 
}; 

//Used to update each object 
Asteroid.prototype.update = function() { 
    this.x += Math.random(); 
    this.y += Math.random(); 
}; 

//Updates all the objects by calling the prototype each second 
setInterval(function() { 
    Asteroid.prototype.update(); 
},1000); 

내가 그 값을 얻을 수 없다는 프로토 타입에 오류 메시지가 "X", 그래서 모든 개체를 업데이트하기 위해 사용하는 적절한 방법은 무엇입니까?

답변

4

당신은 Asteroid예를update() 작업을 수행해야합니다

// Updates all the objects by calling the prototype each second 
setInterval(function() { 
    asteroids.forEach(function(a) { a.update(); }); 
}, 1000); 

Asteroid.prototype.update()Asteroid의 모든 인스턴스에 update 메소드를 호출하지 않습니다 호출. 도움을


또한 독서

+0

감사합니다! 내가 원하는대로 작동합니다. –

3

프로토 타입에 연결된 함수를 호출하면 모든 인스턴스에 적용되지 않습니다. 그것은 단지 함수입니다. 배열을 반복하고 모든 객체에서 update()를 호출해야합니다.

관련 문제