javascript hasOwnProperty(),in操作符

hasOwnProperty()方法

确定某个对象是否具有带指定名称的属性。

语法

object.hasOwnProperty(proName)

参数

object

必需。对象的实例。

proName

必需。一个属性名称的字符串值。

使用hasOwnProperty()方法可以检测一个属性是存在于实例中,还是存在于原型中。这个方法只在给定属性存在于对象实例中时,才会返回true

结合之前讲的代码实例,我们再来看一下hasOwnProperty()方法的使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script type="text/javascript">
        function Person(){
        }

        Person.prototype.name="Nicholas";
        Person.prototype.age=29;
        Person.prototype.job="software Engineer";
        Person.prototype.sayName=function(){
            return this.name;
        }

        var person1=new Person();
        var person2=new Person();

        document.write(person1.hasOwnProperty("name"));
        document.write("<br>");
        document.write("name" in person1);
  </body>
</html>

output:

false
true

上面代码中我顺道也写出来了in操作符的结果,下面我们来讲讲in操作符。

in操作符会在通过对象能够访问给定属性时返回true,无论属性存在于实例中还是原型中。

在《javascript高级程序设计》中为了确定属性到底是存在原型中还是存在于实例中。书中同时用到了hasOwnProperty()方法与in操作符,并且写出了一个函数,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <script type="text/javascript">

        function hasPrototypeProperty(object,name){
            return !object.hasOwnProperty(name) && (name in object);
        }

        function Person(){
        }

        Person.prototype.name="Nicholas";
        Person.prototype.age=29;
        Person.prototype.job="software Engineer";
        Person.prototype.sayName=function(){
            return this.name;
        }

        var person1=new Person();
        var person2=new Person();

        document.write(person1.hasOwnProperty("name"));
        document.write("<br>");
        document.write("name" in person1);
        document.write("<br>");


        document.write(hasPrototypeProperty(person1,"name"));
        document.write("<br>");
        person1.name="xiaohong";
        document.write(hasPrototypeProperty(person1,"name"));
    </script>
</body>
</html>

output:
false
true
true
false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值