这怎么可能呢?访问对象变量

时间:2017-09-22 15:10:48

标签: javascript variables object

这怎么可能?我想在前两个例子中它应该返回undefined。

function SecretCode() {
    var _secretNum = 78;

    this.guessNum = function(num) {
        if(num > _secretNum) {
            return console.log("Lower"); 
        } else if (num < _secretNum) {
            return console.log("Higher");
        } else {
            return console.log("You guessed it");
        } 
    }
}

let secret = new SecretCode();
secret.guessNum(this.secretNum);    //You guessed it
secret.guessNum(this._secretNum);   //You guessed it
secret.guessNum(secretNum);         //is not defined
secret.guessNum(_secretNum);        //is not defined
console.log(secret.secretNum);      //undefined
console.log(secret._secretNum);     //undefined

3 个答案:

答案 0 :(得分:3)

是的,作为函数调用的参数,this.secretNumthis._secretNum都是未定义的。但num > undefinednum < undefined都返回false。因此,if结构除了进入第3分支外没有其他可能性。

答案 1 :(得分:0)

前两个例子写出&#34;你猜对了#34;因为this.secretNum解析为undefined,因此num参数解析为undefined,因此(num > _secretNum)(num < _secretNum)都不是真的。 this._secretNum;

当然也是如此

答案 2 :(得分:0)

我已经针对每一行添加了评论。希望这会很有用

<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <p>Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text.
    Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text.Here will be a text. Here will be a text.
    Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text.Here will be a text. Here will be a text. Here will be a text.
    Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text. Here will be a text.</p>

</body>

</html>