zoukankan      html  css  js  c++  java
  • 构造函数-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);会提示错误

    原型链: 

  • 相关阅读:
    详解Redis中两种持久化机制RDB和AOF(面试常问,工作常用)
    IDEA链接数据库自动生成实体类
    urllib的高级用法
    django项目部署上线
    Git 远程仓库(Github)
    git 标签
    git分支管理
    Git 工作区、暂存区和版本库
    git介绍及安装
    Python3-笔记-numpy学习指南-002-基础
  • 原文地址:https://www.cnblogs.com/p201821460026/p/13714379.html
Copyright © 2011-2022 走看看