Prototype source code analysis-object Part 2: type detection

Source: Internet
Author: User

Nonsense:

Originally, this prototype source code analysis was intended only for taking notes on Prototype Learning. However, sometimes a problem can be found to be more in-depth (although it is still an analysis), which breaks away from the original expectations, more and more questions. Today, I plan to write STR, but when I write it to the variable detection, I find that the process can be dragged down again. This is definitely not good for projects, but it is unclear about learning.

Because of the loss you have suffered, from the perspective of a newbie, write as much as possible for new beginners.

 

Here, I don't care how various types are defined in Javascript. The only thing to point out is:

var str_1 = 'xesam';
var str_2 = new String('xesam');
console.log(str_1 === str_2);

Here, str_1 and str_2 are not the same thing. Previously I saw someone in the group mentioned a similar problem, so I remembered it.

Checks the type of a variable. The most common is the typeof operator.

The return value of typeof is a string. Generally, only the following results can be returned: Number, Boolean, String, function, object, undefined

However, if we want to differentiate specific classes such as date and Regexp, there is no way for typeof, so it is unified into the object.

Let's take a look at some definitions in prototype:

      NULL_TYPE = 'Null',
UNDEFINED_TYPE = 'Undefined',
BOOLEAN_TYPE = 'Boolean',
NUMBER_TYPE = 'Number',
STRING_TYPE = 'String',
OBJECT_TYPE = 'Object',
FUNCTION_CLASS = '[object Function]',
BOOLEAN_CLASS = '[object Boolean]',
NUMBER_CLASS = '[object Number]',
STRING_CLASS = '[object String]',
ARRAY_CLASS = '[object Array]',
DATE_CLASS = '[object Date]',

[The values of these variables are returned as specified results to avoid human errors]

Return to the variable detection,

Let's look at an instance:

    var array_1 = [null,undefined,10,NaN,'10',true,function(){}];
var array_2 = [new Function(),new String(),new Number(),new Boolean(true),{},[],/x/,new Error(),new Date()];
var varArray = array_1.concat(array_2);
(function(){
for(var i in varArray){
console.log(typeof varArray[i]);
}
})();

The result is as follows:

Pay attention to the following:

Null --> Object

Nan --> Number

All functions except functions with the new operator are objects.

We wrap this process in prototype format. As a general process, the null and undefined processes are specially handled first:

(Function (){
// Define a string of the type
VaR typemap = {
'Number': 'number ',
'Boolean': 'boolean ',
'String': 'string ',
'Function': 'function ',
'Object': 'object ',
'Undefined': 'undefined ',
'Null': 'null'
};
Function Type (OBJ ){
Switch (OBJ) {// detect null and undefined
Case NULL :{
Return typemap ['null'];
}
Case undefined :{
Return typemap ['undefined'];
}
}
VaR objtype = typeof OBJ;
Switch (objtype ){
Case 'number ':{
Return typemap ['number'];
}
Case 'boolean ':{
Return typemap ['boolean'];
}
Case 'string ':{
Return typemap ['string'];
}
Case 'function ':{
Return typemap ['function'];
}
Case 'object ':{
Return typemap ['object'];
}
}
}
For (var I in vararray ){
Console. Log (type (vararray [I]);
}
})();

[Note]

Or the above example is simpler:

    (function(){
function type(obj){
return obj === null ? 'Null' :
obj === undefined ? 'Undefined' :
typeof obj === 'number' ? 'Number':
typeof obj === 'boolean' ? 'Boolean':
typeof obj === 'string' ? 'String':
typeof obj === 'function' ? 'Function': 'Object';
}
for(var i in varArray){
console.log(type(varArray[i]));
}
})();

Running result:

Now we have separated the "Basic Type". [here, the basic type refers to the types that can be detected by typeof, not the basic JS type. Don't spray me ···]

The next step is to separate the types in the object. Two methods are provided:

1. Convert to string form

2. detection prototype

Method 1:

First, the string representation of the object is obtained. There are several methods to obtain the string format:

var obj = 'xesam';
obj = ''+obj;
obj = String(obj);
obj = obj.toString();

The tostring () method of the object is called for output methods such as alert and consystemic. It is reasonable to say that there is no problem, but date, Regexp, array and so on all rewrite the tostring method inherited from the object, so what is returned cannot be predicted.

Therefore, you must use the original object. Prototype. tostring.
Use the original object. prototype. tostring is limited to being unable to judge a custom class. Unless the custom class overwrites its own tostring method, overwriting the tostring method of the custom class will cause enumeration (in) (the first part of the object has been mentioned), so we need to carefully consider this.

The specific implementation is as follows:

   (function(){
function objectType(obj){
obj = Object.prototype.toString.call(obj);
return obj;
}
for(var i in varArray_2){
console.log(objectType(varArray_2[i]));
}
})();

Running result:

The second method is to call the instanceof operator.

For example:

console.log([] instanceof Array);

This is the form of variable instanceof constructor.

Or directly judge the constructor.

Specific implementation:

    (function(){
function objectType(obj){
obj = obj.constructor;
return obj === Array ? '[object Array]':
obj === Boolean ? '[object Boolean]':
obj === Date ? '[object Date]':
obj === RegExp ? '[object RegExp]':
obj === String ? '[object String]':
obj === Function? '[object Function]':
obj === Error ? '[object Error]':
obj === Number ? '[object Number]':'[object Object]'
}
for(var i in varArray_2){
console.log(objectType(varArray_2[i]));
}
})();

Running result:

This can also obtain the corresponding results for the custom class, just a little bit of code.

For more information, see http://www.cnblogs.com/xesam /]
Address: http://www.cnblogs.com/xesam/archive/2011/12/21/2296146.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.