小微型庫(2.typeOf 功能和獲取innerHTML)

liangsheng0111發表於2018-11-01

實現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)的基礎上繼續新增功能

  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
複製程式碼

  1. 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;
        }
    }
    
}
複製程式碼

相關文章