Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object twice produces different results

I have the javascript code below. On Chrome, Firefox, Android emulator, Firefox on a Samsung Galaxy S (Gingerbread 2.3.3), and Safari on an iPod it works fine. On the native browser on the Samsung Galaxy S it does not.

The code creates an object and tests the values on the object. The first time it creates the objects it's correct. The second time it creates the object the values are not correct.

Is this a bug in the Javascript or V8 or the device? How would you go about resolving it?

var Padding = function(pleft, ptop, pright, pbottom) {
    this.top = 20;
    this.left = 1;
    this.right = 0;
    this.bottom = 0;
    this.left = pleft;
    this.top = ptop;
    this.right = pright;
    this.bottom = pbottom;
};

function testPadding() {
    var p;
    p = new Padding(91, 92, 93, 94);
    alert(p.left.toString() + "," + p.top.toString() + "," + p.right.toString() + "," + p.bottom.toString());
}

testPadding();  // 91,92,93,94 - correct
testPadding(); // 1,20,93,0 - should be 91,92,93,94
testPadding(); // 1,20,93,0 - should be 91,92,93,94

EDIT: I've found why it works in the emulator. The emulator uses a different javascript engine. It uses JSC instead of V8. There is a snippet of code in http://code.google.com/p/android/issues/detail?id=12987 that helps you work out what engine it uses. The emulator uses JSC, the Samsung Galaxy S uses V8.

like image 824
dan gibson Avatar asked Oct 18 '11 01:10

dan gibson


1 Answers

Because of how the V8 Engine does garbage collection and Caching, I imagine it is not done with the object before it starts to return a result. Have you tried changing your code to the following? Does it return the expected result each time with this code instead?

var Padding = function(pleft, ptop, pright, pbottom) {
    this.top = (ptop != null) ? ptop : 20;
    this.left = (pleft!= null) ? pleft: 1;
    this.right = (pright!= null) ? pright: 0;
    this.bottom = (pbottom!= null) ? pbottom: 0;
};

function testPadding() {
    var p;
    p = new Padding(91, 92, 93, 94);
    alert(p.left.toString() + "," + p.top.toString() + "," + p.right.toString() + "," + p.bottom.toString());
}

testPadding(); // ?
testPadding(); // ?
testPadding(); // ?
like image 155
Nikkoli Avatar answered Nov 09 '22 14:11

Nikkoli