← 返回首页
Javascript基础教程(四十五)
发表时间:2021-07-12 20:05:58
原型对象

每一个Javascript对象都有原型对象,该对象可以使用原型对象上的属性和方法。

1.类对象和对象

在Javascript中类对象的原型对象是prototype,而类的对象的原型对象是__proto__。简单说就是使用类对象有prototype属性,只有对象有__proto__属性。

一个对象默认继承自Object,因此它的原型对象与Object的原型对象相同。

例如:

    function Person(name,age){
        this.name = name;
        this.age = age;
    }
    let p = new Person('zhangsan',20);
    console.log(Person.prototype===p.__proto__);
    console.log(Object.prototype===Person.prototype.__proto__);

运行结果:
true
true

2.在原型对象上扩展新的属性或者方法

注意:这里我们改变的只是prototype和__proto__指向对象的属性和方法,并没有改变这个引用的地址。 例如:

    function Animal(height,weight){
        this.height = height;
        this.weight = weight;
    }

    let a = new Animal();
    console.log(a.__proto__ === Animal.prototype);

    //在类的prototype上扩展
    Animal.prototype.eat=function(){
        console.log('animal eating...');
    }
    //在对象的__proto__属性上扩展
    a.__proto__.bark=function(){
        console.log('animal barking...');
    }

    a.eat();
    a.bark();

    let b = new Animal();
    console.log('创建新对象后....');
    b.eat();
    b.bark();

运行结果:
true
animal eating...
animal barking...
创建新对象后....
animal eating...
animal barking...

3.原型实现继承

    function Animal(height,weight){
        this.height = height;
        this.weight = weight;
    }
    Animal.prototype.eat=function(){
        console.log('animal eating...');
    }

    function Human(name){
        this.name = name;
    }

    Human.prototype = new Animal();
    Human.prototype.think=function(){
        console.log(this.name+" is thinking...");
    }

    let person = new Human('zhangsan');
    person.eat();
    person.think();

运行结果:
animal eating...
zhangsan is thinking...

4.在Object的prototype上扩展

    function Animal(height,weight){
        this.height = height;
        this.weight = weight;
    }
    Animal.prototype.eat=function(){
        console.log('animal eating...');
    }

    function Human(name){
        this.name = name;
    }

    Human.prototype = new Animal();

    Object.prototype.think=function(){
        console.log(this.name+" is thinking...");
    }

    let person = new Human('zhangsan');
    person.eat();
    person.think();

    let obj = {name:'lisi'};
    obj.think();

运行结果:
animal eating...
zhangsan is thinking...
lisi is thinking...