我有下面的 javascript 代码。在 Chrome、Firefox、Android 模拟器、Samsung Galaxy S(Gingerbread 2.3.3)上的 Firefox 和 iPod 上的 Safari 上,它工作正常。在 Samsung Galaxy S 的 native 浏览器上,它没有。
该代码创建一个对象并测试该对象的值。它第一次创建对象时是正确的。第二次创建对象时,值不正确。
这是 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
编辑:我已经找到它在模拟器中工作的原因。模拟器使用不同的 javascript 引擎。它使用 JSC 而不是 V8。 http://code.google.com/p/android/issues/detail?id=12987中有一段代码这可以帮助您确定它使用的是什么引擎。模拟器使用 JSC,Samsung Galaxy S 使用 V8。
最佳答案
由于 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(); // ?
关于javascript - 两次创建一个对象会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801579/