How does Javascript know what type a variable is?

后端 未结 4 597
遇见更好的自我
遇见更好的自我 2020-12-06 13:52

I don\'t know why I never asked myself that questioned the last years before, but suddenly I could not find any answer for myself or with google.

Javascript is known

4条回答
  •  一向
    一向 (楼主)
    2020-12-06 14:32

    One simple way to imagine an implementation is that all values are kept in objects and that all variables are pointers... in C++:

    struct Value
    {
        int type;
        Value(int type) : type(type) { }
        virtual ~Value() { }
    
        virtual std::string toString() = 0;
    };
    
    struct String : Value
    {
        std::string x;
        String(const std::string& x) : Value(STRING_TYPE), x(x) { }
        virtual std::string toString()
        {
            return x;
        }
    };
    
    struct Number : Value
    {
        double x;
        Number(double x) : Value(NUMBER_TYPE), x(x) { }
        ...
    };
    
    struct Object : Value
    {
        // NOTE: A javascript object is stored as a map from property
        //       names to Value*, not Value. The key is a string but
        //       the value can be anything
        std::map x;
        Object() : Value(OBJECT_TYPE), x(x) { }
        ...
    };
    

    For example whenever an operation has to be performed (e.g. a+b) you need to check the types of the objects pointed by the variables to decide what to do.

    Note that this is an ultra-simplistic explanation... javascript today is much more sophisticated and optimized than this, but you should be able to get a rough picture.

提交回复
热议问题