JS之原型对象

时间:2023-03-09 19:01:31
JS之原型对象

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>