自有屬性和共有屬性:
自有屬性:直接保存在對象本地的屬性
共有屬性:保存在原型對象中,被全部子對象共享的屬性
獲取時:均可用對象.屬性方法
賦值時:自有屬性,必須:對象.屬性 = 值
共有屬性,必須:構造函數.prototype.屬性 = 值
鑑別自有仍是共有:
自有:var bool = obj.hasOwnProperty('屬性名')
判斷「屬性名」是不是obj的自有屬性
共有:不是自有,且obj.屬性名!==undefined
其中:in:判斷obj本身或obj的父對象中是否包含"屬性名"。只要本身或父對象中包含,就 返回true。
共有:相同寫的 屬性名 in obj
if(obj.
hasOwnProperty
(pname)){
console.log('自有屬性')
}else if(obj[pname]!==undefined){ // 可改寫成:
}else if(pname in obj){
console.log('共有屬性')
}else {
console.log('沒有這個屬性!')
}
------------------------------------------------------------------------------------------------------
例:判斷是否是自有屬性hasOwnProperty方法
//自有屬性
function Student(sname,sage){
this.sname =sname;
this.sage =sage;
}
//共有屬性
Student.prototype.intr=function(){
console.log(`I am ${this.sname},I am ${this.sage}`)
}
//共有屬性
Student.prototype.className="初一二班";
var lilei =new Student('Li Lei',11);
var hmm =new Student('Han Meimei',12);
//判斷是否是自有屬性函數
function checkProperty(obj,pname){
if(obj.hasOwnProperty(pname)){
console.log('自有屬性')
}else if
(obj[pname]!==undefined)
{ // 可改寫成:
}else if(pname in obj){
console.log('共有屬性')
}else {
console.log('沒有這個屬性!')
}
}
checkProperty(lilei,"sname"); //自有
checkProperty(hmm,"className");//共有
checkProperty(lilei,"bal");//沒有
var o={x:1}
console.log(o.hasOwnProperty("x")) //true
console.log(o.hasOwnProperty("y")) //false
------------------------------------------------------------------------------------------------------