我正在尝试将 PHP 类翻译成 JavaScript。我唯一遇到的麻烦是从数组变量中获取一个项目。我创建了一个简单的 jsfiddle here .我不明白为什么它不起作用。
(编辑:我更新了这段代码以更好地反射(reflect)我在做什么。对之前的错误感到抱歉。)
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 经验的人可能能够弄清楚情况。
Edit2: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
关于Javascript 数组未定义......我不确定为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642969/