怎么判断某个属性是自身的还是原型链上的

118 阅读1分钟

想要判断某个属性是自身的还是原型链上的需要结合hasOwnProperty()方法和in运算符
原型链上继承过来的属性不能被hasOwnProperty检测到会返回false

function Student(){
}
Student.prototype.name='123';
var student = new Student();
student.hasOwnProperty('name'); // false
<!------------------------------>
student.name='123';
student.hasOwnProperty('name'); // ture

但是这样不能区分属性在原型链上还是不存在所以需要结合in运算符

function Student(){
}
Student.prototype.name='123';
var student = new Student();
console.log('name' in student); // true
<!------------------------------>
student.name='123';
console.log('name' in student); // true

最终:

function inAndHasOwnProperty(obj,atr){
	return (atr in obj)&&(obj.hasOwnProperty(atr));
	//如果返回true就是在自身上,false则在原型链上
}