Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Something QUIRKY About 'instanceof' and '__proto__' #58

Open
josephmax opened this issue Nov 9, 2018 · 4 comments
Open

Something QUIRKY About 'instanceof' and '__proto__' #58

josephmax opened this issue Nov 9, 2018 · 4 comments

Comments

@josephmax
Copy link

我在浏览器里做了如下实验

var a = new String('123')
// undefined
a instanceof String
// true
a instanceof Object
// true
a.__proto__ === String.prototype
// true
a.__proto__.__proto__ === Object.prototype
// true

但是当我使用字面量定义的时候

var b = '123'
b instanceof String
// false
b instanceof Object
// false
b.__proto__ === String.prototype
// true
b.__proto__.__proto__ === Object.prototype
// true

所以字面量赋值这是什么魔法。。。可以保留__proto__的指向的同时骗过instanceof的判断?

instanceof on MDN

@Beace
Copy link

Beace commented Nov 9, 2018

@josephmax 参考: string vs object string by mdn

image

@houjunjie
Copy link

houjunjie commented Nov 9, 2018

也不是说骗过instanceofinstanceof是用来测试prototype属性是否在某对象的原型链当中。
但是prototype属性是只有函数才有的,字面量赋值是javascript自动转成相应的类型对象,不是使用构造函数创建,所以是没有prototype的。

关于__proto__prototype,可以看这篇文章creeperyang/blog#9

个人觉得还不错

@josephmax
Copy link
Author

@Beace 好的,我就是在找这个动态语言执行时规则的解释,感谢

@josephmax
Copy link
Author

@houjunjie instance instanceof Constructor是检查Constructorprototype是否在instance的原型链上, b instanceof String,说明引擎认为String的prototype不在b的原型链上。但是通过访问b.__proto__却能访问到String.prototype。这是我这个例子想表达的点。�

楼上提供的解释我觉得ok, 就是说当一个字面量被创建的时候,它的确不是一个复杂对象。但当你访问b.__proto__的时候,引擎将它解释为了一个String的实例去处理。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants