Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"JSPatch 实现原理详解"这篇文章最后关于js中false以及Boolean对象的说明有误。 #351

Closed
rob2468 opened this issue May 10, 2016 · 3 comments

Comments

@rob2468
Copy link
Contributor

rob2468 commented May 10, 2016

原文链接:https://github.com/bang590/JSPatch/wiki/JSPatch-%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%AF%A6%E8%A7%A3
原文描述:
“题外话,神奇的 JS 里 false 的 this 竟然不再是原来的 false,而是另一个 Boolean 对象,太特殊了:
Object.prototype.c = function(){console.log(this === false)};
false.c() //output false”

===比较时,this是临时包装对象,false是原始值,返回false是应该的。

若写成如下语句,返回为true。

  1. this.valueOf() === false;
  2. this == false;
@bang590
Copy link
Owner

bang590 commented May 23, 2016

已在原文加链接

@bang590 bang590 closed this as completed May 23, 2016
@dreampiggy
Copy link

'use strict';
Object.prototype.c = function(){console.log(this === false)};
false.c() //output true

@wanhmr
Copy link

wanhmr commented Mar 14, 2021

有没有加 'use strict' 确实结果不一样。

Object.prototype.c = function() {
    console.log('this:')
    console.log(this)
    console.log('typeof(this):')
    console.log(typeof(this))
    console.log('typeof(false):')
    console.log(typeof(false))
    console.log('typeof(Boolean(0))')
    console.log(typeof(Boolean(0)))
    console.log('this.valueOf():')
    console.log(this.valueOf())
    console.log('this == false:')
    console.log(this == false)
    console.log('this === false:')
    console.log(this === false)
}
false.c()

output:
this:
[Boolean: false]
typeof(this):
object
typeof(false):
boolean
typeof(Boolean(0))
boolean
this.valueOf():
false
this == false:
true
this === false:
false
'use strict' 
Object.prototype.c = function() {
    console.log('this:')
    console.log(this)
    console.log('typeof(this):')
    console.log(typeof(this))
    console.log('typeof(false):')
    console.log(typeof(false))
    console.log('typeof(Boolean(0))')
    console.log(typeof(Boolean(0)))
    console.log('this.valueOf():')
    console.log(this.valueOf())
    console.log('this == false:')
    console.log(this == false)
    console.log('this === false:')
    console.log(this === false)
}
false.c()

output:
this: 
false
typeof(this):
boolean
typeof(false):
boolean
typeof(Boolean(0))
boolean
this.valueOf():
false
this == false:
true
this === false:
true

从输出来看,没有 'use strict' 的结果是比较好理解,因为 false false 是 primitive value,调用 c 函数的时候会进行隐式转换为 Boolean。而由于 === 不会进行隐式转换所以导致 this === false 输出 false

而加上 'use strict' 就比较奇怪,没看懂。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants