Home >Web Front-end >JS Tutorial >Alternative writing methods for defining methods in Javascript (methods to define js objects in batches)_javascript skills

Alternative writing methods for defining methods in Javascript (methods to define js objects in batches)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:10:22861browse
Copy code The code is as follows:

isArray : function(v){
return toString.apply( v) === '[object Array]';
},
isDate : function(v){
return toString.apply(v) === '[object Date]';
},
isObject : function(v){
return !!v && Object.prototype.toString.call(v) === '[object Object]';
},
isPrimitive : function(v){
return Ext.isString(v) || Ext.isNumber(v) || Ext.isBoolean(v);
},
isFunction : function(v){
return toString.apply(v) === '[object Function]';
},
isNumber : function(v){
return typeof v === 'number' && isFinite(v);
},
isString : function(v){
return typeof v === 'string';
},
isBoolean : function(v){
return typeof v = == 'boolean';
}

The above is the code to determine the type in Extjs3.X ext-base.js. If you look carefully, you will find that there are many similar things, such as :
Copy code The code is as follows:

is type: function(v){
return toString.apply(v) ==="Type";
}
or
is type: function(v){
returntypeof v ==="Type";
}

However, for tyoeof inside, we can use the toString method to determine the type. All the above codes can be of the same type, that is:
Copy Code The code is as follows:

var is type=function(v){
return toString.call(v) ==="type";
}

The above is a model, and the method corresponding to this judgment is a method. We can simplify it (but there is a drawback: poor readability), which can greatly reduce the code. This can improve Javascript loading efficiency. The improved code is as follows:
Copy code The code is as follows:

var Easy={}, dataTypes = ["Number", "Boolean", "String", "Array",
"Object", "Function", "Date", "RegExp"];
var toStr = Object.prototype.toString;
var is = function (v, t) {
return toStr(o) == "[object " t "]";
};
for ( var i = 0, len = dataTypes.length, t; i < len; i ) {
(function (t) {
Easy["is" t] = function (o) {
return is(o, t);
}
})(dataTypes[i]);//Using closure
}

For the above code, we will The Easy object has created 8 methods that start with is to determine the type; of course, if some methods are unreasonable, you can also override them, such as:
Copy code The code is as follows:

Easy.isNumber=function(v){
return toString.call(v) ==="[object Number]"&& isFinite(v);
}

So sometimes you can consider this writing method when writing some methods with similar functions. I am hungry and went to eat. I will introduce it here this time. I will talk about it next time.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn