两次创建对象会产生不同的结果

dan*_*son 13 javascript android v8

我有下面的javascript代码.在Chrome,Firefox,Android模拟器,三星Galaxy S(Gingerbread 2.3.3)上的Firefox和iPod上的Safari上运行正常.在三星Galaxy S上的本机浏览器上它没有.

代码创建一个对象并测试对象上的值.第一次创建对象时它是正确的.第二次创建对象时,值不正确.

这是Javascript或V8或设备中的错误吗?你会如何解决它?

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
Run Code Online (Sandbox Code Playgroud)

编辑:我发现它为什么在模拟器中工作.模拟器使用不同的JavaScript引擎.它使用JSC而不是V8.http://code.google.com/p/android/issues/detail?id=12987中有一段代码可帮助您确定使用的引擎.模拟器使用JSC,三星Galaxy S使用V8.

Nik*_*oli 1

由于 V8 引擎如何进行垃圾收集和缓存,我想在开始返回结果之前,对象还没有完成。您是否尝试过将代码更改为以下内容?它每次使用此代码都会返回预期结果吗?

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(); // ?
Run Code Online (Sandbox Code Playgroud)