!!表达式为布尔值

Dev*_*555 5 javascript

我正在阅读John Resig的JavaScript Ninja秘密,并看到了这段代码:

 function Ninja(){
   this.swung = false;

   // Should return true
   this.swingSword = function(){
     return !!this.swung;
   };
 }
Run Code Online (Sandbox Code Playgroud)

我知道!!用于将表达式转换为布尔值.但我的问题是他为什么使用:

return !!this.swung;
Run Code Online (Sandbox Code Playgroud)

这不是多余的,因为swung它已经是一个布尔变量或我错过了什么?

BTW这里是完整的相关代码以防万一:

 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."
)
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 6

this.swung不是局部变量,而是Ninja实例的属性.因此,可以通过外部方法修改属性.

为了确保swingSword始终返回布尔值,使用显式转换!!很有用.

至于你的代码:我认为,它应该是!this.swung,因为!!this.swung回报falsethis.swung = false:

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
Run Code Online (Sandbox Code Playgroud)