• 对象原型


    如何判断一个对象的方法是来自这个本身的还是原型的?

    function Person() {
    }
     
    Person.prototype.name="Nicholas";
    Person.prototype.age=29;
    Person.prototype.sayName=function(){
        alert(this.name);
    }
     
    var person1=new Person();
    person1.name="Greg";
     
    var person2=new Person();
     
    console.log(person1.hasOwnProperty("name"));//true
    console.log(person2.hasOwnProperty("name"));//false
     
    console.log("name" in person1);//true
    console.log("name" in person2);//true
     
    for (var prop in person1) {
        console.log(prop);//name   age   sayName
    }
     
    function hasPrototypeProperty(object,pro) {//如此可判断存在于原型中的属性
        return (!object.hasOwnProperty(pro))&&(pro in object);
    }
    console.log(hasPrototypeProperty(person1,"name"));//false
    console.log(hasPrototypeProperty(person2,"name"));//true
    function Person() {
    }
     
    Person.prototype.name="Nicholas";
    Person.prototype.age=29;
    Person.prototype.sayName=function(){
        alert(this.name);
    }
     
    var person1=new Person();
    person1.name="Greg";
     
    var person2=new Person();
     
    console.log(person1.hasOwnProperty("name"));//true
    console.log(person2.hasOwnProperty("name"));//false
     
    console.log("name" in person1);//true
    console.log("name" in person2);//true
     
    for (var prop in person1) {
        console.log(prop);//name   age   sayName
    }
     
    function hasPrototypeProperty(object,pro) {//如此可判断存在于原型中的属性
        return (!object.hasOwnProperty(pro))&&(pro in object);
    }
    console.log(hasPrototypeProperty(person1,"name"));//false
    console.log(hasPrototypeProperty(person2,"name"));//true

     

  • 相关阅读:
    追寻缺失的大学精神 一个民族需要关注天空的人
    图论简介
    18个分形图形的GIF动画演示
    平行宇宙
    eclipse经常出现——未响应!!!
    单例模式
    Java内存区域
    编译与解释(java)
    正则表达式判断QQ号格式是否正确
    正则表达式判断手机号格式是否正确
  • 原文地址:https://www.cnblogs.com/yuaima/p/5901557.html
Copyright © 2020-2023  润新知