构造函数-prototype

 function Start(uname, age) {
      this.uname = uname;
      this.age = age;

      this.sayhai = function () {
        console.log('hi');
      }

    }
   var zjl = new Start('zjl', '41');
    var reol = new Start('reol', '22');

以上的构造函数中,new了zjl和reol两个对象,存在一个sayhai的方法,二者的内容一样,但由于方法为复杂数据类型,会分别开辟一个新的内存空间,白白浪费了内存,可以使用构造函数内置的属性prototype,将一些不变的方法定义在其原型对象上,达到节省内存的目的

 function Start(uname, age) {
      this.uname = uname;
      this.age = age;

      // this.sayhai = function () {
      //   console.log('hi');
      // }

    }

    //核心
    Start.prototype.sayhai = function () {
      console.log('hi');
    }

    var zjl = new Start('zjl', '41');
    var reol = new Start('reol', '22');

    zjl.sayhai();

最后的输出正常,但内存被节省了

其构造出来的对象之所以能调用prototype,是因为zjl中系统自动添加了指向prototype的原型对象的属性,__proto__

__proto__与prototype是等价的,console.log(zjl.__proto__===Star.prototype);输出为true

系统会在prototype和__proto__中自动添加constructor的属性,其指向原来的构造函数即Star

输出

 console.log(zjl.__proto__.constructor);

输出结果为:

但是,如果这样赋值,则会自动覆盖掉系统生成的constructor

 Start.prototype = {
      sayhi: function () {
        console.log('hi');
      }
    }

则输出 console.log(zjl.__proto__.constructor);会提示错误

原型链: 

原文地址:https://www.cnblogs.com/p201821460026/p/13714379.html