Home > Web Front-end > JS Tutorial > JavaScript hasOwnProperty() function (picture and text tutorial, with code examples)

JavaScript hasOwnProperty() function (picture and text tutorial, with code examples)

亚连
Release: 2018-05-21 15:04:54
Original
1745 people have browsed it

hasOwnProperty() function is used to indicate whether an object itself (excluding the prototype chain) has a property with the specified name. Let’s share with you an example of the JavaScript hasOwnProperty() function through this article. Friends who are interested should take a look

hasOwnProperty() The function is used to indicate an object itself (excluding the prototype chain) Whether there is an attribute with the specified name. If there is, return true, otherwise return false.

This method belongs to the Object object. Since all objects "inherit" the object instance of Object, almost all instance objects can use this method.

Major browsers such as IE 5.5, FireFox, Chrome, Safari, and Opera all support this function.

Syntax

object.hasOwnProperty( propertyName )
Copy after login

Parameters

ParametersDescription
propertyNameString type Specified property name

返回值

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
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JavaScript isPrototypeOf和hasOwnProperty使用区别(实用)

在JavaScript中对原型prototype全面分析

重点讲解在JavaScript中的__proto__属性(图文教程)

The above is the detailed content of JavaScript hasOwnProperty() function (picture and text tutorial, with code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template