javascript hasOwnProperty and prototype

后端 未结 3 1707
旧时难觅i
旧时难觅i 2020-12-20 22:29
function Animal(name,numLegs){
this.name = name;
this.numLegs = numLegs}

Animal.prototype.sayName = function(){
console.log(\"Hi my name is \" + this.name );}

var          


        
相关标签:
3条回答
  • 2020-12-20 23:02

    Because hasOwnProperty check the property is present or not in itself, not as an inherited one form prototypes, read this

    This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

    0 讨论(0)
  • 2020-12-20 23:16

    Because 'sayname' is inherited from 'Animal' its not 'penguin' own property.

    check : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

    similar example :

    function Foo() {
      this.value = 'qwert';
    }
    Foo.prototype.say = "hello";
    
    var foo = new Foo();
    
    foo.hasOwnProperty("say"); // False, since say is inherited from the prototype object.
    foo.hasOwnProperty("value"); // True, since value is the property of foo itself.
    
    0 讨论(0)
  • 2020-12-20 23:18

    When JavaScript is looking for a property, it first looks into the object itself. If it isn't there, it normally keeps walking up the prototype chain. hasOwnProperty exists to check only the object itself, explicitly not walking up the prototype chain. If you want to check if a property exists at all, checking everything in the prototype chain, use the in operator:

    'sayName' in penguin  // => true
    
    0 讨论(0)
提交回复
热议问题