Should hasOwnProperty still be used with for..in statements

前端 未结 3 535

There are a lot of blogs saying that a hasOwnProperty check should be used whenever the for..in loop is used, but I don\'t understand why that\'s t

3条回答
  •  鱼传尺愫
    2020-12-10 04:54

    Without hasOwnProperty you don't know whether the property is a native property of your object or inherited from it's prototype.

    Your modified fiddle

    var obj1 = {a:"10",b:"20"};
    
    Object.prototype.c = "prototype:30";
    
    var i;
    for(i in obj1) {
        document.getElementById("div1").innerHTML += obj1[i]+" ";
    }
    // result 10 20 prototype:30
    
    for(i in obj1) {
        if(obj1.hasOwnProperty(i)) {
            document.getElementById("div2").innerHTML += obj1[i] +" ";
        }          
    }
    // result 10 20
    ​
    

    In this case obj1 inherits the property c from it's Prototype Object and you would erroneously list it in your first loop.

提交回复
热议问题