账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    JS类型判断
    17
    0

    问题: 对 instanceof 的疑惑

    根据MDN关于 instanceof 的描述:
    object instanceof constructor
    instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

    关于字面量字符串不能理解为什么不是String的实例。

    MDN有这样的例子:

    var simpleStr = "This is a simple string"; 
    var myString  = new String();
    var newStr    = new String("String created with constructor");
    
    simpleStr instanceof String; // returns false, 检查原型链会找到 undefined
    myString  instanceof String; // returns true
    newStr    instanceof String; // returns true
    myString  instanceof Object; // returns true

    不太理解这里的检查原型链会找到undefined

    我自己测试的时候发现

    const s = "abcdefg";
    
    s instanceof String; // false
    
    s.__proto__ === String.prototype; // true

    这里字面量字符串的原型链不是有String.prototype吗,那么为什么字面量字符串却不是String的实例?

    另外,这是我看到别人写的 instanceof

    function instance_of(L, R) {//L 表示左表达式,R 表示右表达式
     var O = R.prototype;// 取 R 的显示原型
     L = L.__proto__;// 取 L 的隐式原型
     while (true) { 
       if (L === null) 
         return false; 
       if (O === L)// 这里重点:当 O 严格等于 L 时,返回 true 
         return true; 
       L = L.__proto__; 
     } 
    }
    
    const s = "abc";
    
    instance_of(s, String); // true

    这个实现,得到的字面量字符串是String的实例,那么实现上是哪里出了问题?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部