• 2.原型与in操作符




    // in有两种用法,一种是使用在for-in循环中,一种是单独使用。单独使用时,in操作符会在对象可以访问给定属性时返回true



    function Person(){

    }
    Person.prototype.name="summer";
    Person.prototype.age=20;
    Person.prototype.job="enginner";
    Person.prototype.sayName=function(){
    console.log(this.name);
    }
    var person1=new Person();
    var person2=new Person();
    console.log(person1.hasOwnProperty("name")); // false
    console.log("name" in person1); // true

    person1.name="summer2";
    console.log(person1.name); // summer2---来自实例
    console.log(person1.hasOwnProperty("name")); // true
    console.log("name" in person1); // true

    console.log(person2.name); // summer---来自原型
    console.log(person2.hasOwnProperty("name")); // false
    console.log("name" in person2); // true

    // in操作符只要通过对象能访问到属性就返回true,hasOwnProperty只在属性存在于实例中时才返回true,
    // 因此只要in操作符返回true,hasOwnProperty返回false时可以确定该属性是原型中的属性

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

    function Person(){

    }
    Person.prototype.name="summer";
    Person.prototype.age=20;
    Person.prototype.job="enginner";
    Person.prototype.sayName=function(){
    console.log(this.name);
    }

    var person= new Person();
    alert(hasPrototypePropty(person,"name")); // true
    person.name="su";
    alert(hasPrototypePropty(person,"name")); // false



  • 相关阅读:
    java环境配置
    关于Chrome(谷歌浏览器)对docume,准确获取网页客户区的宽高、滚动条宽高、滚动条Left和Top
    CSS3圆角详解
    Js监控回车事件
    Sql日期时间格式转换
    JS操作JSON总结
    SQL日期操作及只获取日期的方法
    如何让div出现滚动条
    CodeForces 55D Beautiful numbers
    POJ 3034 Whac-a-Mole
  • 原文地址:https://www.cnblogs.com/liululu/p/5820646.html
Copyright © 2020-2023  润新知