_proto_和prototype区别

  • 每个对象都有一个__proto__属性,并且指向它的prototype原型对象
  • 每个构造函数都有一个prototype原型对象

prototype原型对象里的constructor指向构造函数本身

示例1

  • class Person {
    constructor(options) {
    this.name = options.name || '';
    }
    getName() {
    return '我的名字是:'+this.name;

    }
    }

  • let person = new Person({
    name: 'yes',

})

  • 打印
    console.log(person.proto);
    console.log(Person.prototype);
  • 返回 原型对象 {constructor:xxx,getName:xxx }

console.log(Person.prototype.constructor)

  • 返回 class Person

非class的原写法

  • function Person2(options){
    this.name=options.name;
    }
  • Person2.prototype.getName=function(){
    return this.name;
    }
  • let person2= new Person2({
    name: 'yes'
    })
    console.log('person2',person2.proto);
    console.log('person2',Person2.prototype);
  • 返回 对象 {constructor:xxx,getName:xxx }

console.log(person2.proto===Person2.prototype); //true

继承实现:实例对象的_proto_ 指向构造函数的prototype.

查找对象属性步骤。

设对象a;

  • 查找对象a的属性,找到后返回;
  • 没找到,通过对象a的_proto_找到原型对象。并在原型对象上找,找到返回;
  • 没找到,把a的原型对象按第二步骤继续......,期间找到返回,没找到进入下一步。
  • 原型链终点null。Object.prototype.proto===null。没找到结束返回undefined。
  • 如:
  • Person.prototype.sayName = function () {
    return 'sayName:' + this.name;
    }
    console.log(person.sayName());
    实例后,在原型上添加属性,仍可以访问到。
    也可以使用实例对象的__proto__属性新增方法

继承

一个对象可以使用另外一个对象的属性和方法。

  • 根据示例2 函数Person2
    创建一个对象。拥有对象person的属性。
  • function Man(){

}

  • Man.prototype=new Person2({name: 'man'});
    let man=new Man();
    console.log(man.name);

类继承 extends,super
class Woman extends Person{

}

  • 原型链顶端-
    Object.prototype.proto: null
原文地址:https://www.cnblogs.com/alaner/p/15331913.html