美文网首页
《JavaScript高级程序设计第三版》读书笔记2

《JavaScript高级程序设计第三版》读书笔记2

作者: 柯基糖 | 来源:发表于2016-10-18 17:15 被阅读0次

    1、检测数组:

    • typeof运算符不能检测数组
      console.log(typeof ["长老姓糖","25"]);//object
    • ECMAScript 5的isArray函数是原生的检测方法,但低版本浏览器不支持
    function isArray(obj) { 
        return Array.isArray(obj);
    }
    var arr = ["长老姓糖","25"]; //创建一个数组
    isArray(arr); // true
    
    • 对象自身的constructor属性和instanceof操作符虽然也能检测数组,但在frame中会产生问题
    var arr =  ["长老姓糖","25"];
    console.log(arr.constructor === Array); // true
    console.log(arr instanceof Array); // true
    
    // 创建iframe并添加到DOM中
    var iframe = document.createElement('iframe'); //创建iframe
    document.body.appendChild(iframe); //将创建的iframe添加到body中
    otherArray = window.frames[window.frames.length - 1].Array;
    var arr = new otherArray("长老姓糖","25"); //声明数组 ["长老姓糖","25"]
    console.log(arr instanceof Array); // false
    console.log(arr.constructor === Array); // false
    
    • 对象原生toString检测也能检测数组
    isArray = function(obj) { 
    return Object.prototype.toString.call(obj) == "[object Array]";}
    var arr = ["长老姓糖","25"];
    console.log(isArray(arr)); // true
    
    • 最佳检测方法
    var isArray = (function () { 
        if (Array.isArray()) { 
            return Array.isArray(); 
        } 
        return function (subject) { 
            return Object.prototype.toString.call(subject) ===  "[object Array]"; 
        };
    }());
    var arr = [];
    isArray(arr); // true
    

    具体内容请参考此链接。

    2、检测属性:
    JavaScript对象的属性分为两种存在形态. 一种是存在实例中, 另一是存在原型对象中.

    根据上述, 检测属性的时候会出现4种情况
    既不存在实例中, 也不存在原型对象中
    存在实例中, 不存在原型对象中
    不存在实例中, 存在原型对象中
    既存在实例中, 也存在原型对象中

    可以用in运算符。var object={ name="",age=""};利用if("name" in object){...}就可以了;

    另外可以用object.hasOwnProperty()函数来判断实例属性(如果这个属性存在于该对象的原型中,则返回false),另外在Dom对象中,因为Dom对象并不继承自object,所以并没有这个方法,应该先检测DOM对象存不存在。

    结合in操作符和hasOwnProperty()就可以自定义函数来检测原型中是否存在给定的属性.

    functino Person() {};
    Person.prototype.name = 'apple';
    var person1 = new Person();
    var person2 = new Person();
    person1.name = 'banana';
    
    function hasPrototypeProperty(object, name) {     
        return !object.hasOwnPrototype(name) && (name in object);
    }
    console.log(hasPrototypeProperty(person1, 'name')); //false
    console.log(hasPrototypeProperty(person2, 'name')); //true
    

    原型中存在给定属性, 返回true(情况3). 否则返回false(情况1/情况2/情况4).

    相关文章

      网友评论

          本文标题:《JavaScript高级程序设计第三版》读书笔记2

          本文链接:https://www.haomeiwen.com/subject/qtrtuttx.html