ES5原理笔记

ES5原理

类的本质就是函数

函数的调用:

  1.普通调用:函数名()
  2.构造函数调用:new 函数名():生成了一个新的对象  
  例:
     function Person() {       类,构造函数
       console.log(555);
    }
  函数的调用
   let p1=new Person();
   console.log(p1);         →555  person{}

   let p2=Person();
   console.log(p2);         →undefined

方法的调用

    构造函数部分
    function Person(name) {
        this.name = name;
    }
    原型部分
    Person.prototype.sayHello = function () {
        console.log(this.name);
    }
    Person.prototype.sayGoodBye = function () {
        console.log(this.name, "bye");
    }

原型 prototype

     函数表达式
     let foo1 = function(){

     };
     声明
     function foo2(){

     };
     构造函数
     let foo3 = new Function();

     console.log(foo2);
     foo2 = 5;
     console.log(foo2);

数据类型

基本:6个(string、symbol、number、boolean、undefined、null)

引用:1个(对象)/无数个(万物皆对象,一个类就是一个类型)

原型链

1.函数对象都有一个属性,prototype(原型),原型的作用是给所有实例提供公共访问。

2.所有对象都有一个proto(隐式原型),只想创建该对象的构造函数的原型。

3.prototype(原型)上有一个属性constructor,指向原型所在的类。

4.prototype其实就是一个普通的对象。

5.Object.prototype.proto===null

通过proto逐级向上 查找,查找至值为 null (也就是 Object.prototype)时结束。

   toString: ƒ toString() :: 复杂数据类型隐式转换为字符串的方法
   valueOf: ƒ valueOf():: 复杂数据类型隐式转换为原始值的方法

ES5继承: 方法借用(call) + 原型继承

    function Animal(name,age){
        this.name = name;
        this.age = age;
    }
    Animal.prototype.move = function(){
        console.log(this.name+"正在移动");
    }

call,apply,bind:强行绑定this的方法

    function Bird(name,age,flyColor){
            方法借用:
        // const temp = this;
        // temp.Animal = Animal;
        // temp.Animal(name,age);
        // delete temp.Animal; 

        Animal.call(this,name,age);     等同于  super(name,age)
        this.flyColor = flyColor;
    }

Object.create(obj):以obj为隐式原型创建空对象

    Bird.prototype = Object.create(Animal.prototype);
    Bird.prototype.constructor = Bird;  
    Bird.prototype.sing = function(){
        console.log(this.name+"正在唱歌");
    }

    const b1 = new Bird("zs",1,"red");
    console.log(b1);
posted @ 2020-05-27 17:42  逸柯c  阅读(57)  评论(0)    收藏  举报