小微型库(2.typeOf 功能和获取innerHTML)

实现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;
        }
    }
    
}
复制代码

转载于:https://juejin.im/post/5bdaa078e51d45688942a240

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值