实现typeOf的功能
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(/\w/)); // [object RegExp]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(NaN)); // [object Number]
console.log(Object.prototype.toString.call("")); // [object String]
console.log(Object.prototype.toString.call(true)); // [object Boolean]
console.log(Object.prototype.toString.call(1)); // [object Number]
console.log(Object.prototype.toString.call([])); // [object Array]
console.log(Object.prototype.toString.call({})); // [object Object]
console.log(Object.prototype.toString.call(new Date)); // [object Date]
console.log(Object.prototype.toString.call(function(){})); // [object Function]
console.log(Object.prototype.toString.call(Math)); // [object Math]
复制代码
注:用call是因为方法用的是别人的,讲this指向自己.
在(1)的基础上继续添加功能
- typeOf功能设置为Liang类的的一个静态方法
Liang.type = function(obj){
//获取object原型的toString方法
var toString = Object.prototype.toString,
//typeOf 可以确定un,num,str,bool,其他的则需要用toString在确定.
type = {
"undefined" : "undefined",
"number" : "number",
"string" : "string",
"boolean" : "boolean",
"[object RegExp]" : "regexp",
"[object Null]" : "null",
"[object Array]" : "array",
"[object Date]" : "date",
"[object Function]" : "function",
"[object Math]" : "math"
};
return type[typeOf obj] || toString.call(obj) || (obj ? "objcet" : "null");
}
复制代码
测试: 在html文件中
console.log($.type(undefined)); //undefined
console.log($.type(boolean)); //boolean
console.log($.type([]])); //object
console.log($.type(new Date)); //date
复制代码
- innerHTML的获取写在Liang.prototype内
Liang.prototype = function(){
constructor : Liang,
init : function(){}, //在(1)
html : function(str){
if(Liang.type(obj) === "undefined"){
//如果type方法的返回值为 undefined,则说明是获取innerHTML
var val = this[0].innerHTML;
return val;
}else{
//设置文本内容
Liang.each(this, function(v){
v.innerHTML = str;
});
return this;
}
}
}
复制代码