You define getX2 twice, each time you create a new A. The result for this function will always be the last X. Considering rewriting your code as follows:
function A(x) { this.x = x; this.getX1 = function() { return this.x; } } A.prototype.getX2 = function() { return this.x; } var a1 = new A(1); var a2 = new A(2); console.log('a1.getX1()=%d', a1.getX1());
This way you only define getX2 once, and it works as expected.
source share