2012-02-21 1 views
4

のための式:!!私はJavaScriptの忍者</strong>のジョンResig氏の<strong>秘密を読み、このコードを見たブール

function Ninja(){ 
    this.swung = false; 

    // Should return true 
    this.swingSword = function(){ 
    return !!this.swung; 
    }; 
} 

私は!!がブールへの発現を変換するために使用されて知っています。しかし、私の質問は、なぜ彼が使用していている:swungはすでにブール変数であるか、私は何かが欠けていますので、

return !!this.swung; 

はその冗長ではないですか?

function Ninja(){ 
    this.swung = false; 

    // Should return true 
    this.swingSword = function(){ 
    return !!this.swung; 
    }; 
} 

// Should return false, but will be overridden 
Ninja.prototype.swingSword = function(){ 
    return this.swung; 
}; 

var ninja = new Ninja(); 
assert(ninja.swingSword(), "Calling the instance method, not the prototype method." 
) 
+0

ただ、推測は - 私はそれはあなたが 'swingSword'関数はブール値を返します知っているように、読みやすくするためだと思います。 –

+0

"trueを返すべきです"というのは、奇妙なコメントです...本当に返さなければならない場合は、単にtrueを返すことができます。右? – Rudie

答えて

5

this.swungないローカル変数が、Ninjaのインスタンスのプロパティ:ところで、ここで

は、念のため、関連するコードがいっぱいです。したがって、プロパティは外部メソッドで変更できます。

swingSwordが常にブール値を返すようにするには、!!を使用する明示的な変換が便利です。あなたのコードについては

:私は!!this.swung戻りthis.swung = falseためfalseので、それは、!this.swungであることを信じている:

this.swung = false;           // Defined in code 
!!this.swung === !!false;         // See previous line 
       !!false === !true;       // Boolean logic 
          !true === false;    // Boolean logic 
             false === this.swung; // See first line 
+0

try ninja.swung = "foobar";アサルトの前に。 – jishi

+0

ああ、それは唯一の正当な理由かもしれません。ありがとう – Dev555

関連する問題