JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

9.5.2 The constructor property

9.5.2 The constructor property

Another way to identify the class of an object is to simply use the constructorproperty. Since constructors are the public face of classes, this is a straightforward approach. For example:

function typeAndValue(x) {

if (x == null) return ""; // Null and undefined don't have constructors

switch(x.constructor) {

case Number: return "Number: " + x; // Works for primitive types

case String: return "String: '" + x + "'";

case Date: return "Date: " + x; // And for built-in types

case RegExp: return "Regexp: " + x;

case Complex: return "Complex: " + x; // And for user-defined types



Note that the expressions following the case keyword in the code above are functions. If we were using the typeof operator or extracting the class attribute of the object, they would be strings instead.

This technique of using the constructor property is subject to the same problem as instanceof. It won’t always work when there are multiple execution contexts (such as multiple frames in a browser window) that share values. In this situation, each frame has its own set of constructor functions: the Array constructor in one frame is not the same as the Array constructor in another frame.

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1