Js中判斷一個屬性是屬於原型函式還是例項屬性的方法
阿新 • • 發佈:2019-01-30
/** * * 檢測一個屬性是例項屬性還是原型屬性 * 檢測完成以後,再來作操作 * */ function Person(password) { this.password = password; } Person.prototype.username = 'luohao'; let person = new Person(123); /** * 可以訪問到例項中的物件,也可以訪問到原型中的的物件。 */ console.log('password' in person); console.log('username' in person); console.log(person.hasOwnProperty('username')); console.log(person.hasOwnProperty('password')); /** * 可以通過hasOwnProperty判斷一個屬性是否是例項的屬性 * 但是無法判斷一個例項是原型的屬性,因為原型的屬性在例項中可以訪問到 */ function hasOwnProperty(obejct, prop) { if (prop in obejct) { if (obejct.hasOwnProperty(prop)) { console.log(prop + '是例項的屬性'); } else { console.log(prop + '是原型的屬性'); } } else { console.log('不存在' + prop + '這個屬性'); } } hasOwnProperty(person, 'username'); hasOwnProperty(person, 'password');