Why are inherited (is there any confusion if they are inherited at all) properties are listed in javascript?

I knew that the inherited properties are not listed. The following code stanfordinherits a property levelfrom another object university.

But when I list stanford, I see that the inherited property is also displayed. Please explain the question (I must be wrong somewhere).

var university = {level:"bachelor"};

var stanford = Object.create(university);
stanford.country = "USA";
stanford.rating = "Good";

console.log(Object.hasOwnProperty("level"));    //  false

for(var properties in stanford){                //  level, country, rating
    console.log(properties);
}
+4
source share
3 answers

Such a wonderful link !! Thanks @Sajib Biswas for this question.

Refer object-getownpropertynames-vs-object-keys

how-do-i-enumerate-the-properties-of-a-javascript-object

, :

var proto = Object.defineProperties({}, {
  protoEnumTrue: { value: 1, enumerable: true },
  protoEnumFalse: { value: 2, enumerable: false }
});
var obj = Object.create(proto, {
  objEnumTrue: { value: 1, enumerable: true },
  objEnumFalse: { value: 2, enumerable: false }
});

for (var x in obj) console.log(x);

Results: 

objEnumTrue
protoEnumTrue


console.log(Object.keys(obj)); // ["objEnumTrue"]
console.log(Object.getOwnPropertyNames(obj)); //  ["objEnumTrue", "objEnumFalse"]

, , .

Object.getOwnPropertyNames(a) a. Object.keys(a) .

:

var university = {level:"bachelor"};

var stanford = Object.create(university);
stanford.country = "USA";
stanford.rating = "Good";

console.log(university.hasOwnProperty("level"));    //  true
console.log(university.hasOwnProperty("country"));    //  false

console.log(stanford.hasOwnProperty("country"));    //  true
console.log(stanford.hasOwnProperty("level"));    //  false
+1

?

Javascript : Data Accessor. Data . enumeration , Object.defineProperty().
:

 var stanford = Object.create(university);
    stanford.country = "USA";
    stanford.rating = "Good";
    Object.defineProperty(stanford, 'rating', {
        enumerable: false
    });

 console.log(Object.keys(stanford)); // Now you won't see 'rating' here
 // the same effect takes place for loop operators (for;;) , for .. in ..)
+1

stanford -:

enter image description here

As you can see, it inherits another object that has a property levelbut does not have "hasOwnProperty" level. However, it for..inwill iterate over all the properties.

+1
source

Source: https://habr.com/ru/post/1621775/


All Articles