Should hasOwnProperty still be used with for..in statements

前端 未结 3 541

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 05:15

    Often you will get the same result with or without hasOwnProperty, but the latter ignores properties that are inherited rather than living directly on the object in question.

    Consider this basic inheritance system. Dogs inherit from the master Animal class.

    function Animal(params) { this.is_animal = true; }
    function Dog(params) { for (var i in params) this[i] = params[i]; }
    Dog.prototype = new Animal();
    var fido = new Dog({name: 'Fido'});
    

    If we peer into fido, hasOwnProperty helps us ascertain which are its own properties (name) and which are inherited.

    for (var i in fido) if (fido.hasOwnProperty(i)) alert(i+' = '+fido[i]);
    

    ...alerts name=Fido but not is_animal=true.

提交回复
热议问题