• JavaScript的原型链


    首先介绍下原型~
    原型的作用:把方法放到原型中,就可以让同类型的对象共享 。

    当我创建一个构造函数。构造函数里有原型。通过:构造函数名.prototype获取到当前构造函数的原型。

    function Student(name,age,gender) {
          // 属性
          this.name = name;
          this.age = age;
          this.gender = gender;
          // 方法
          this.writeCode = function() {
            console.log('我会写代码')
          };
          this.sayHi = function(){
            // 方法内部中this,代表的是调用方法的对象
            console.log('我叫' + this.name + ',今年' + this.age);
          };
        }
    

      

    原型内部自带一个constructor,代表的就是构造函数

        // 获取原型:
        var yx = Student.prototype;
        // 原型内部自带一个constructor,代表的是构造函数
        // 构造函数和原型的关系:
        // 构造函数可以通过  prototype  获取到原型
        // 原型可以通过 constructor  找到构造函数
        console.log(yx.constructor  === Student);  // true;
    

     实例对象与原型之间的关系:
        ① 先从对象本身中查找,若查找不到
        ② 则通过对象自带 proto提供的原型地址,找到原型
        ③ 从原型中去查找

    // 学生类→ 构造函数
     function Student(name, age, gender) {
       // 属性
       this.name = name;
       this.age = age;
       this.gender = gender;
    
     }
    
     // 获取原型
     var yx = Student.prototype;
     // 把不变的属性放入原型中
     yx.type='学生';
    
     // 创建对象
     var zs = new Student('张三', 10, '男');
    
     // 对象可以访问得到原型中成员
     console.log(zs.type); // 学生
     console.log(zs.__proto__ === yx)  // true
    

      

     
  • 相关阅读:

    链表
    队列
    稀疏数组
    SQL——流程控制
    SQL——存储过程与函数
    SOA
    MVC模式
    《一线架构师实践指南》--阅读笔记三
    《一线架构师实践指南》-阅读笔记二
  • 原文地址:https://www.cnblogs.com/JiAyInNnNn/p/11049578.html
Copyright © 2020-2023  润新知