Javascript 数组未定义...我不确定为什么
我正在尝试将 PHP 类转换为 JavaScript。我遇到的唯一麻烦是从数组变量中获取一个项目。我创建了一个简单的 jsfiddle 此处 。我不明白为什么它不起作用。
(编辑:我更新了此代码以更好地反映我正在做的事情。对之前的错误深表歉意。)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
在这里工作正常,您只需不调用
classname();
定义函数后即可。
更新
当您调用 *make_prediction* 时, this 将不在范围内。您创建 that 变量的做法非常正确,请在 *make_prediction* 上使用它:
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
您可以在此处查看工作版本: http://jsfiddle.net/zKcpC/
这实际上非常复杂,我相信在 Javascript 方面更有经验的人可能能够澄清这种情况。
编辑 2:Douglas Crockfords 用这些话来解释:
By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
要查看完整文章,请前往: http://javascript.crockford.com/private.html
您从未调用过
classname
。似乎运行正常。
对我有用:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
您实际上是否调用了
classname
函数?请注意,我将代码块包装在:
([your_code]());