This is the third day of my participation in the August Text Challenge.More challenges in August
preface
Why can the string ‘ABC’ call the length attribute? The string ‘ABC’ is not itself an object. Operator to call length?
The prototype approach
At first I thought ‘ABC’ could call the length attribute. It must be because ‘ABC’ is an instance of String and length is the prototypical method. Naturally can call, so simply write a few sentences.
console.log('abc'.length) / / 3
console.log('abc' instanceof String) // false
Copy the code
Instanceof is used to determine if a variable is an instanceof an object. If instanceof is false, the String ‘ABC’ is not an instanceof a String, so there is no such thing as an inherited archetypal method!
How did that happen?
A concept wrapper object is referenced here
Packaging object
The wrapper object refers to the Number, String, and Boolean native objects corresponding to the Number, String, and Boolean values respectively. Under certain conditions, the original data type will also be automatically converted into objects, so everything is an object.
var v1 = new Number(123);
var v2 = new String('abc');
var v3 = new Boolean(true);
typeof v1 // "object"
typeof v2 // "object"
typeof v3 // "object"
v1 === 123 // false
v2 === 'abc' // false
v3 === true // false
Copy the code
Number(value),String(STR),Boolean(value); Boolean(value);
// The string is converted to a number
Number('111') / / 111
// The value is converted to a string
String(111) / / "111"
// The value is converted to a Boolean value
Boolean(111) // true
Copy the code
So when is a primitive type value automatically converted to a wrapper object, calling a method on that wrapper object?
'abc'.length / / 3
Copy the code
The case will turn automatically, and the JavaScript engine will automatically turn it into a wrapper object on which to call the Length property. After the call, the temporary object is destroyed. This is called automatic conversion of primitive types to instance objects. The code above is equivalent to
var str = 'abc'
var strObj = new String(str)
// String {
// 0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"
// }
strObj.length // 3, call its own property 'length', destroy immediately.
Copy the code
The last
So the summary is, string or number, can call a certain method or attribute, the JS engine will default to the corresponding wrapper type, use the method or attribute above the wrapper type. Instead of calling methods and properties on the prototype chain.