This is the 22nd day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

preface

Before is busy with business development, the basic knowledge of front end to check what are used, rarely has time to sink down and their induction, summarizes the basis, sometimes, what use, feel worthy of pay attention to the thing, are also recorded in his note, also not timely, and then as time goes by, one record everything is at sixes and sevens, I haven’t done it yet. This time, write the basic series of the front end

I plan to chat in a relaxed, chatty tone. If I’m not good at writing, I’ll let you know

Quickly review

We’ve looked at built-in types, primitive types and objects in JS

  1. Primitive types are also called primitive types
  2. Object types are also called reference types
  3. Primitive types store values, object types store addresses (Pointers)

The typeof, instanceof

These two guys, in the actual business development, the frequency of use is not high, but speaking of JS foundation, or carry out to talk about

Typeof is explained in MDN as follows

The typeof operator returns a string representing the typeof the unevaluated operand.

Does typeOF determine the type correctly? I thought I could detect all the types, but it turned out not to be

Typeof displays the correct type for primitive types except null

typeof 1 // 'number' 
typeof '1' // 'string' 
typeof undefined // 'undefined' 
typeof true // 'boolean' 
typeof Symbol(a)// 'symbol'alternativetypeof(null) // 'object'
Copy the code

For objects, all but functions display object, so typeOF can’t tell exactly what type a variable is

typeof(toString) // 'function'
typeof console.log // 'function'

typeof [] // 'object' 
typeof {} // 'object' 

Copy the code

If we want to determine the correct typeof an object, typeof has some trouble

This is a good time to consider instanceof because the internal mechanics are judged by the prototype chain.

Typeof is explained in MDN as follows

The instanceof operator is used to check whether the constructor’s prototype property appears on the prototype chain of an instance object.

As for the prototype chain, my own understanding is that the prototype chain is compared to a base class, and instanceof is just like a method to judge the type of the base class. By defining the method of the object, an object can be obtained, and the type of the object can be determined by its method Instanceof.

const Person = function() {}; 
const p1 = new Person(); 
p1 instanceof Person; // true 

var str = 'hello world';
str instanceof String; // false

var str1 = new String('hello world');
str1 instanceof String; // true

instanceofIt's just a way of determining the type of the prototype chainCopy the code

For primitive types, you can’t just use instanceof to determine the type

The zha do? There are ways for Instanceof to determine the primitive type

class PrimitiveString {
    static [Symbol.hasInstance](x) {
        return typeof x === 'string'}}console.log('hello world' instanceof PrimitiveString) // true
Copy the code

Explain: Typeof ‘Hello world’ === ‘string’ = ‘hello World’ === ‘string’ So of course it’s true. This is a reflection of the fact that Instanceof is not 100% reliable.

Under normal conditions, basic Typeof and Instanceof can be dried in one shuttle, but to sweep the base, it is better to go through it

Type conversion

There are only three types of conversion in JS:

  • Converts to a Boolean value
  • Convert to numbers
  • Convert to string

Turns a Boolean

All values except undefined, null, false, NaN, “”, 0, -0 are converted to true for conditional judgments, including all objects.

Object to primitive type

The built-in [[ToPrimitive]] function is called when the object is converted. For this function, the algorithm logic is generally as follows:

  • If it is already a primitive type, no conversion is required
  • Called if it needs to be converted to a stringx.toString()Returns the converted value when converted to the underlying type. Call first if it is not a stringvalueOfIf the result is not an underlying typetoString
  • callx.valueOf(), returns the converted value if converted to an underlying type
  • If none of them return the primitive type, an error is reported

Of course, you can override symbol. toPrimitive, which has the highest priority when converting to a primitive type.

let a = { 
    valueOf() { 
        return 0 
    }, 
    toString() { 
        return '1'},Symbol.toPrimitive]() {
        return 2}}1 + a / / = > 3
Copy the code

Four operators

The addition operator differs from the other operators in that it has the following characteristics:

  • If one of the operations is a string, the other is converted to a string.Implicit conversion, I don't have to say much about that)
  • If one party is not a string or number, it is converted to a number or string
1 + '1' / / '11'
true + true / / 2
4 + [1.2.3] 41, 2, 3 "/ /"
Copy the code

If you have any questions about the answer, please look at the explanation:

  • For the first line of code, the trigger feature one, so the number1Convert to a string and get the result'11'
  • For the second line of code, triggering characteristic two, so willtrueConverted to digital1
  • For the third line of code, property two is triggered, so the array is passedtoStringConvert to string1, 2, 3, get the result41, 2, 3

In JS, true is 1, false is 0, so

And the other thing to notice about addition is this expression ‘a’ + + ‘b’, which is not very common, because plus ‘b’ is NaN, so it’s “aNaN”, don’t ask why, because that’s what the console prints, right

You might also see the + ‘1’ form in some code to get the number type quickly. You might also see the + ‘1’ form in some code to get the number type quickly.

So for operators other than addition, as long as one of them is a number, the other one is converted to a number (I’m familiar with this, I use this a lot in code, and sometimes I use * instead of parseInt).

4 * '3' / / 12
4 * [] / / 0
4 * [22.33] // NaN
Copy the code

Comparison operator

  1. If it’s an object, it passestoPrimitiveConverting objects
  2. If it is a string, it passesunicodeCharacter index to compare
let a = { 
    valueOf() { 
        return 0
    },
    toString() { 
        return '1' 
    } 
} 

a > -1 // true
Copy the code

In the above code, because a is an object, valueOf converts it to the original type and compares the values.

conclusion

  1. Typeof and instanceof
  2. Type conversion

Ps: Dry words or more boring, and hard to impress, we are still in daily use, more experience