前言
// 在js中有很多语法糖的存在,如
let obj = {
...
}
其实就是
let obj = new Object(....)
let arr = [...]
即
let arr = new Array(.....)
let fun = function(a, b){
....
}
即
let fun = new Function('a', 'b', '函数体...')
// 这些语法糖都会使得即使是直接赋值,没有new对应的构造函数, 但其隐式原型依旧指向对应的原型对象, 同时其也是实例对象
console.log(obj instanceof Obejct); // true
console.log(arr instanceof Array); // true
console.log(fun instanceof Function); // true
正题
// 但string是包装类
let str = "asd";
console.log(str.__proto__ === String.prototype); // true 隐式原型指向String的原型对象
console.log(str.constructor === String); //true 也有从String的原型对象上继承下来的constructor属性
//!但却不是String的实例,但明明前面比较隐式原型与原型对象时都是true了
console.log(str instanceof String); // false
/*
原因:
【如果尝试着把原始类型(number、string、boolean)当做对象使用,
JS会自动将其转换为对应包装类的实例】
在读取str的时候会创建一个临时性的对象, 称为包装对象,即在读取str的属性的时候,
js会把str通过new String来创建一个实例对象然后在引用结束后立即销毁
*/
// 只有通过new的方式才能创建String的实例对象
let str2 = new String('abc');
console.log(str2 instanceof String); // true