JavaScript中hasOwnProperty与isPrototypeOf方法详解

作者:木棉时间:2026-10-28 12:10:07浏览:91

本文介绍JavaScript中hasOwnProperty和isPrototypeOf两个核心方法的用法。hasOwnProperty用于判断属性是否存在于对象自身,忽略原型链;isPrototypeOf用于检测对象是否处于指定对象的原型链中。结合siteAdmin构造函数示例,展示如何区分实例属性与原型方法,以及原型链的验证逻辑。

hasOwnProperty与isPrototypeOf方法定义

hasOwnProperty方法用于检测对象是否拥有指定的自身属性。需要特别注意,该方法不会检查原型链上的属性,仅针对对象自身的成员进行判断。

isPrototypeOf方法用于确定一个对象是否存在于另一个对象的原型链中。如果指定对象位于实例的原型链上,则返回true,否则返回false。

代码实现与原型链验证

具体实现代码如下:

function siteAdmin(nickName,siteName){
this.nickName=nickName;
this.siteName=siteName;
}
siteAdmin.prototype.showAdmin = function() {
alert(this.nickName+"是"+this.siteName+"的站长!")
};
siteAdmin.prototype.showSite = function(siteUrl) {
this.siteUrl=siteUrl;
return this.siteName+"的地址是"+this.siteUrl;
};
var matou=new siteAdmin("本站","WEB前端开发");
var matou2=new siteAdmin("本站","WEB前端开发");
matou.age="30";
// matou.showAdmin();
// alert(matou.showSite("https://www.jb51.net/"));
alert(matou.hasOwnProperty("nickName"));//true
alert(matou.hasOwnProperty("age"));//true
alert(matou.hasOwnProperty("showAdmin"));//false
alert(matou.hasOwnProperty("siteUrl"));//false
alert(siteAdmin.prototype.hasOwnProperty("showAdmin"));//true
alert(siteAdmin.prototype.hasOwnProperty("siteUrl"));//false
alert(siteAdmin.prototype.isPrototypeOf(matou))//true
alert(siteAdmin.prototype.isPrototypeOf(matou2))//true
作者最新文章