Javascript通过引用访问成员变量

时间:2016-03-28 02:04:38

标签: javascript asynchronous scope pass-by-reference

我正在编写一个javascript应用程序,我想在全球范围内访问我的应用程序变量。像这样:

//Initialize 
var myApp=new app();

//Count is zero here, as expected since app is asynchronous
console.log(myApp.count);

//But 5 seconds later, count should have a non-zero value
setTimeout(function(){ 
    console.log(myApp.count); 
}, 5000);

应用程序代码:

//Application code
function app() {

    var count=0;

    setTimeout(function(){ 
        console.log("Setting count to 10");
        count=10;
    }, 2500);

    //Member variable for count
    this.count=count;
}

在这里查看jsfiddle: https://jsfiddle.net/o4db2ep4/

我想要的是第一次访问count为零,但第二次访问应该是10.

我认为发生的事情是,在我宣布myApp时,它获得count的值为零。这就像价值/参考问题与范围相结合,我正在努力解决这个问题。

如何获得对动态app.count的引用,即始终包含count的当前值,而不是赋值时的值?如果这不可能,我该如何重新思考这个问题呢?

2 个答案:

答案 0 :(得分:1)

正在发生的事情是countthis.count是不同的变量,并且它们并没有神奇地同步。一旦你分配它,这是一次性的事情。当它被分配this.count=count=0时;超时将在此后2500ms发生,此时您要更新的内容为this.count

function app() {

    this.count = 0;

    setTimeout(function(){ 
        console.log("Setting count to 10");
        this.count = 10;
    }.bind(this), 2500);
}

如上所示,您不需要两个变量。

答案 1 :(得分:1)

这个怎么样:

$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);

foreach($field1_name_array as $element){
    $query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
    $query_link = mysqli_query($link,$query);
    if(mysqli_num_rows($query_link)>0){
        $row = mysqli_fetch_assoc($query_link);
        $goodWord = $row['replaceWord'];
        $element= $goodWord;
    }
    $newComment = $newComment." ".$element;
}

//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution

mysqli_close($link);

//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
} 
else{
    die('comment is not set or not containing valid value');
}