Prototypes and in operators

Prototypes and in operators

1. Use the in operator alone: returns true when an object can access a given attribute, whether the attribute exists in the instance or prototype.

function Person(){
}

Person.prototype.name="Nicholas";
Person.prototype.age=29;
Person.prototype.job="SoftWare Engineer";
Person.prototype.sayName=function(){
    console.log(this.name);
};
var person1=new Person();
var person2=new Person();
console.log(person1.hasOwnProperty("name"));//false
console.log("name" in person1);//true
person1.name="yyq";
console.log(person1.hasOwnProperty("name"));//true
console.log("name" in person1);//true

2. Use the in operator to determine whether it is a prototype property

function hasPrototypeProperty(object,name){
	return !object.hasOwnProperty(name)&&(name in object);
}
person1.name="yyq";
console.log(hasPrototypeProperty(person1,"name"));//false
console.log(hasPrototypeProperty(person2,"name"));//true

3. For in loop, which returns all enumerable attributes that can be accessed through objects, including attributes that exist in the prototype and instances. Instance properties that mask non enumerable properties in the prototype will also be returned in the for in loop. Because by convention, all developer defined properties are enumerable.

person1.hobby="painting";
for(var prop in person1){
    console.log(person1[prop]);
}
/*
painting
Nicholas
29
SoftWare Engineer
[Function]
*/
var o={
	toString:function(){
		return "my Object";
	}
};
for(var prop in o){
	console.log(o[prop]);//[Function: toString]
}

4. Two methods to replace for in

To get all enumerable instance properties on an object, use the Object.keys() method of ECMAScript5. This method takes an object as a parameter and returns an array of strings containing all enumerable properties.

var keys=Object.keys(Person.prototype);
console.log(keys);//[ 'name', 'age', 'job', 'sayName' ]
person1.name="Greg";
person1.age="15";
var p1keys=Object.keys(person1);
console.log(p1keys);//[ 'name', 'age' ]

If you want to get all the instance properties, you can use the Object.getOwnPropertyNames() method, regardless of whether it is enumerable or not.

var keys=Object.getOwnPropertyNames(Person.prototype);
console.log(keys);//[ 'constructor', 'name', 'age', 'job', 'sayName' ]
person1.name="Greg";
person1.age="15";
var p1keys=Object.getOwnPropertyNames(person1);
console.log(p1keys);//[ 'name', 'age' ]

5. Default non enumerable properties and methods
hasOwnProperty(), propertyIsEnumerable(), toLocalString(), toString(), and valueOf()

Keywords: Attribute

Added by Nhoj on Thu, 19 Dec 2019 22:45:27 +0200