码迷,mamicode.com
首页 > Web开发 > 详细

JS之理解对象

时间:2016-08-30 00:11:37      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

1.__proto__

每个对象都有一个__proto__属性,指向该对象的原型对象

<script>
        var person = function(name,city){
            this.name = name;
            this.city =city;   
        }
        person.prototype.showName = function(){
            return this.name;   
        }
        var p = new person(pmx,shanghai);
        console.log(p.__proto__ == person.prototype);
</script>

 

2.isPrototypeOf(obj)用来判断当前对象是否是obj的原型对象

<script>
      var person = function(name,city){
            this.name = name;
            this.city =city;   
        }
        person.prototype.showName = function(){
            return this.name;   
        }
        var p = new person(pmx,shanghai);
        console.log(person.prototype.isPrototypeOf(p));
</script>

3.getPrototypeOf(obj)得到obj的原型对象

<script>
      var person = function(name,city){
            this.name = name;
            this.city =city;   
        }
        person.prototype.showName = function(){
            return this.name;   
        }
        var p = new person(pmx,shanghai);
        console.log(Object.getPrototypeOf(p) == person.prototype);
</script>

 

4.hasOwnProperty用来判断属性是存在于本身还是原型对象中

<script>
      var person = function(name,city){
            this.name = name;
            this.city =city;   
        }
        person.prototype.age = 26;
        person.prototype.showName = function(){
            return this.name;   
        }
        var p = new person(pmx,shanghai);
        console.log(p.hasOwnProperty("name"));
        console.log(p.hasOwnProperty("age"));
</script>

 

5.in用来判断obj是否有指定属性,不论该属性存在于对象上,还是原型链上

<script>
      var person = function(name,city){
            this.name = name;
            this.city =city;   
        }
        person.prototype.age = 26;
        person.prototype.showName = function(){
            return this.name;   
        }
        var p = new person(pmx,shanghai);
        console.log("name" in p);
        console.log("age" in p);
</script>

 

JS之理解对象

标签:

原文地址:http://www.cnblogs.com/pmx-pmx/p/5820211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!