• 请不要在回答技术问题时复制粘贴 AI 生成的内容
mytry
V2EX  ›  程序员

一个 JavaScript 挑战题,检测隐形人是否存在~

  •  
  •   mytry · Nov 20, 2018 · 4880 views
    This topic created in 2909 days ago, the information mentioned may be changed or developed.

    检测 Math 对象是否被 Proxy 拦截。(如果有打印 hooked,期望得到 true ;没有则 false )

    在线代码: https://jsfiddle.net/8sdugz9r/

    答案有多个,当然越简单越好~

    15 replies  •  2018-11-21 17:02:36 +08:00
    meepo3927
    meepo3927
    Nov 20, 2018
    1
    if (Math.random() < 0.5)

    是何作用 ?
    mytry
    mytry
    OP
    Nov 20, 2018
    2
    @meepo3927 可以在有没有 Proxy 之间做一个对比
    ljbha007
    ljbha007
    Nov 20, 2018
    3
    试了很多办法 都不行
    gen900
    gen900
    Nov 20, 2018
    4
    @meepo3927 随机替换 Math。
    murmur
    murmur
    Nov 20, 2018
    5
    @meepo3927 以前有在线编程题因为测试用例是给定的被摸出规律 然后返回值 return true 或者 return false 都能过很多例子
    chairuosen
    chairuosen
    Nov 20, 2018
    6
    抖个机灵:
    ```
    else{
    return false
    }
    return true
    ```
    page470075640
    page470075640
    Nov 20, 2018
    7
    ```
    if (Math.random() < 0.5) {
    console.log('hooked')

    self.Math = new Proxy(Math, {
    get(obj, prop) {
    return obj[prop]
    }
    })
    } else {
    return false
    }

    return true


    function self() {}
    ```
    themostlazyman
    themostlazyman
    Nov 20, 2018
    8
    self.Math.random = () => {
    return 1;
    }
    autoxbc
    autoxbc
    Nov 20, 2018❤️2
    9
    function bomb()
    {
    try {
    return bomb()
    } catch(err) {
    try {
    Math.PI
    return false
    } catch(err) {
    return true
    }
    }
    }

    console.log( bomb() )
    TomatoYuyuko
    TomatoYuyuko
    Nov 20, 2018
    10
    @autoxbc #9 666 这是什么蛇皮操作?为啥爆栈之后 err 打印不出来了,而且为啥有代理π会报错,看不懂 QAQ
    autoxbc
    autoxbc
    Nov 20, 2018❤️2
    11
    @TomatoYuyuko #10
    Math 真身和代理的区别是代理多一次 getter 函数调用

    所以先填满栈,再去访问 Math.PI ,失败说明被代理,成功说明是静态对象

    思路来自楼主的上一贴
    https://www.v2ex.com/t/509253
    mytry
    mytry
    OP
    Nov 20, 2018
    12
    @autoxbc 回答正确~ 其实最先是在研究这个问题,然后才虚构了上一贴的问题😄 不过这个问题还有更简单更高效更通用的答案。
    eggggger
    eggggger
    Nov 20, 2018❤️1
    13
    function hasProxy(obj) {
    Object.defineProperty(obj, 'self', {
    get: function() { return this }
    })
    return obj.self !== obj
    }
    mytry
    mytry
    OP
    Nov 20, 2018
    14
    @eggggger 💯
    yuutan
    yuutan
    Nov 21, 2018
    15
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1712 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 14:47 · PVG 22:47 · LAX 06:47 · JFK 09:47
    ♥ Do have faith in what you're doing.