JavaScript hasOwnProperty() 方法详解与原型链区分

作者:闭包旅人时间:2026-10-22 06:43:48浏览:531

本文详解JavaScript中hasOwnProperty()方法,用于判断对象自身是否包含指定属性,不检查原型链。通过示例对比in操作符,展示如何准确区分自有属性与继承属性,适用于IE5.5+及主流浏览器。

hasOwnProperty()方法概述

hasOwnProperty()方法用于判断对象自身(不包含原型链)是否拥有指定的属性名称。若存在该属性则返回true,否则返回false。

该方法定义在Object对象上,由于所有对象都继承了Object的实例,因此绝大多数对象实例均可调用此方法。

包括IE 5.5+、FireFox、Chrome、Safari、Opera在内的主流浏览器均支持此函数。

语法与参数

语法


object.hasOwnProperty( propertyName )

参数

参数 描述
propertyName String类型指定的属性名称

返回值

hasOwnProperty()方法的返回值为Boolean类型。当对象object拥有名为propertyName的属性时,返回true;否则返回false。

此方法仅检查对象自身的属性,不会追溯原型链。只有当属性是对象本身的成员时,才返回true。

代码示例与原型链区分

示例与说明


function Site(){
  this.name = "CodePlayer";
  this.url = "http://www.365mini.com/";
  this.sayHello = function(){
    document.writeln("欢迎来到" + this.name);
  };
}
var obj = {
  engine: "PHP"
  ,sayHi: function(){
    document.writeln("欢迎访问" + this.url);
  }
};
// 使用对象obj覆盖Site本身的prototype属性
Site.prototype = obj;
var s = new Site();
document.writeln( s.hasOwnProperty("name") ); // true
document.writeln( s.hasOwnProperty("sayHello") ); // true
// 以下属性继承自原型链,因此为false
document.writeln( s.hasOwnProperty("engine") ); // false
document.writeln( s.hasOwnProperty("sayHi") ); // false
document.writeln( s.hasOwnProperty("toString") ); // false
// 想要查看对象(包括原型链)是否具备指定的属性,可以使用in操作符
document.writeln( "engine" in s ); // true
document.writeln( "sayHi" in s ); // true
document.writeln( "toString" in s ); // true

总结

以上介绍了JavaScript hasOwnProperty()方法的实例详解,希望有所帮助。如有疑问请留言,小编会及时回复。感谢对本站的支持!

作者最新文章