• js-数据类型


    最近在看视频学习,把相关的知识记录,汇总一下,

    js的原始数据类型包含五种:number、string、boolean、null、undefined

    还有一个大家常见到的也就是object(Date、Function、Array等)

    如何判断类型,主要有以下几种:typeof、instanceof、Object.prototype.toString、constructor、duck type

    1)typeof:适合判断函数和基本类型的判断,例如:

      typeof 1-》‘number’,

      typeof true-》‘boolean’,

      typeof function-》‘function’,

      typeof undefined-》‘undefined’,

      typeof new Object()-》‘object’,

      typeof [1,2]-》‘object’,

      typeof NaN-》‘number’,

      typeof null-》‘object’(历史遗留问题)

    发现没有,对基本类型比较合适,遇到数组,还是object,无法精确区分object,这时候引入instanceof(基于原型链prototype)

    2)instanceof:obj instanceof Object 适合判断对象类型(基于原型链prototype)

    举个例子:

    var child = function (){};
    var parent = function (){};
    child.prototype = new parent();
    var c = new child();
    var p = new parent();
    document.write(c instanceof parent);//true

    有关prototype,可以查询相关的文档,以后我也会在博客中总结一下前人总结的特点

    简单说一下这个例子,每一个实例对象(c,p)都有一个_proto_属性(原型属性),他们会指向自己对象(child,parent)的prototype

    第一步,会判断c的_proto_指向的child的prototype是否等于parent的prototype,不等于,

    第二步,继续找c的上一级的原型,前面定义了child.prototype = new parent();也就是说c的_proto_的_proto_跟parent的prototype是一样的,这里就返回true了

    3)Object.prototype.toString:适合内置对象和基本元素,注意ie的兼容(ie6,7,8 返回[object Object])

    例如:

    Object.prototype.toString.apply([])==='[object Array]';

    Object.prototype.toString.apply(function(){})==='[object Function]';

    Object.prototype.toString.apply(null)==='[object Null]';

    Object.prototype.toString.apply(undefined)==='[object Undefined]';

    这里简单查一下jq的类型判断的部分源码:

    type: function( obj ) {
        return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object";
    },
    isFunction: function( obj ) {
        return jQuery.type(obj) === "function";
    },
    isArray: Array.isArray || function( obj ) {
        return jQuery.type(obj) === "array";
    },
    jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
            class2type[ "[object " + name + "]" ] = name.toLowerCase();
     });

    这里我想说的就是jq的设计技巧,很巧妙的把我们用到的类型,用数组同统一封装一下,js的很多原生的方法在jq也定义了一下。这里借鉴一下这个思路

  • 相关阅读:
    删除ASP.net临时文件的操作步骤
    设置字段必录,但是直接点提交没有检查必录
    JavaWeb-Session
    Java集合类详解 转
    使用COS组件实现文件上传 转
    Java泛型详解 转
    java接口与工厂
    Vector和ArrayList的比较
    ArrayList
    关闭myeclipse自动校验特别是对js文件的校验
  • 原文地址:https://www.cnblogs.com/aishangyizhihu/p/4212057.html
Copyright © 2020-2023  润新知