Why does for(var i in Math) not iterate through Math.* in Javascript?

前端 未结 4 729
旧巷少年郎
旧巷少年郎 2021-02-14 11:19

For some reason for(var i in Math){console.log(i)} doesn\'t show the expected tan, cos, atan2, E, PI in Javascript.

4条回答
  •  花落未央
    2021-02-14 12:06

    I keep noticing when the actual method is not known people will tell you you shoud'nt do it

    The following is the way to expose private functions of a given object

    let exposeFunctionsOf  =(obj) =>
    {
        let iterated = false
        for ( let k in obj ) 
        {
            iterated = true;
            let prop = obj[k]
            if ( typeof props == "function")
            {
                window[k] = prop
            }
        }
        if (!iterated)
        {
           let props_names = Object.getOwnPropertyNames(obj);
           for (let prop_name of props_names)
           {
              iterated = true;
              let prop = obj[prop_name]
              if ( typeof prop == "function")
                window[prop_name] =prop
           }
        }
        if (!iterated)
        {
          console.warn("failed to iterate through the following object")
          cosnole.log(obj)
        }
    }
    

    Applied on Math object

    exposeFunctionsOf(Math)
    

    Now you can write sin(x) instead of Math.sin(x)

    Enjoy

提交回复
热议问题