js中的hasOwnProperty和isPrototypeOf方法使用實例

[js中的hasOwnProperty和isPrototypeOf方法使用實例]

function Parent() {
    this.name = "Parent";
}
Parent.prototype.alertP = function(){
    alert('Parent-alertP');
};

function Child(){
    this.age = 23;
}
Child.prototype.alertC = function(){
    alert('Child-alertC');
};

function Other(){}
Other.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
var child = new Child();
console.log(child);

// instanceof:判斷該對象是否是另一個對象的實例
console.log(child instanceof Parent);   // true
console.log(child instanceof Child);    // true

// isPrototypeOf: 判斷一個對象是否是一個實例的原型
console.log(Parent.isPrototypeOf(child));   // false
console.log(Parent.prototype.isPrototypeOf(child)); // true
console.log(Other.isPrototypeOf(child));    // false
console.log(Other.prototype.isPrototypeOf(child));  // true
console.log(Child.isPrototypeOf(child));    // false
console.log(Child.prototype.isPrototypeOf(child));  // true

// hasOwnProperty: 判斷對象是否有某個特定的屬性
// prototype 是函數才有的屬性,__proto__ 是每個對象都有的屬性(不是所有瀏覽器都有)
console.log(child.__proto__);   // Parent{constructor:function}
console.log(child.prototype);   // undefined
console.log(child.constructor); // function Child() {this.age = 23; }
console.log(Child.hasOwnProperty("name"));  // true
console.log(Parent.hasOwnProperty("name"));  // true
console.log(child.hasOwnProperty("age"));  // true
console.log(Child.hasOwnProperty("age"));  // false
console.log(Parent.hasOwnProperty("age"));  // false
console.log(Child.hasOwnProperty("alertP"));  // false
console.log(Child.__proto__);   // function() {[ native code ]}
console.log(Child.prototype);   // Parent{constructor:function}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容