zoukankan      html  css  js  c++  java
  • 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



  • 相关阅读:
    什么是IOC
    spring的作用
    什么是spring框架?
    72
    71
    70
    69
    68
    67
    66
  • 原文地址:https://www.cnblogs.com/liululu/p/5820646.html
Copyright © 2011-2022 走看看