js构造函数详解

1.什么是构造函数?

  • 首先我们要明白什么是构造函数?

    • 通过 new 函数名 来实例化对象的函数叫构造函数
    • 函数名一般首字母大写驼峰命名(规范)
    • 通过关键字new,会产生一个空对象,这个空对象就是构造函数的返回值,这个对象叫做实例对象
  • 常用的构造函数:

    • var arr = [ ]; 等同于 var arr = new Array(); 的语法。

    • var obj = { } 等同于 var obj = new Object(); 的语法。

    • var date = new Date();

    • 。。。。。

2.执行构造函数都发生了什么?

例如:

 function Student(name,age,score){

            this.name = name;
            this.age = age;
            this.score = score;

               this.exam = function(){

                    console.log('我叫'+this.name+'今年'+this.age+'岁这次考了'+this.score+'分')

               }
        }

        var pyq = new Student('pyq',18,0)
        
        pyq.exam() //我叫pyq今年18岁这次考了0分

1 . var pyq = {}; //创建了一个继承自 Student.prototype 的新对象。

2 . pyq.proto = Student.prototype; // pyq 继承 了Student的原型。

3 . pyq(‘pyq’,18,0); //执行函数,将name,age,score 参数传入,函数内部this 为 new 创建的 pyq对象,this.name = ‘pyq’, this.age=18, this.sore= 0;
4 . 调用了里面的score方法,输出结果 //我叫pyq今年18岁这次考了0分

3.构造函数es6中的写法

  • class 为构造函数的语法,所以 class 的本质是 就是构造函数
        class Student{ //定义一个类名字为Studen
            constructor(name,age,score){//constructor为构造方法可以往里面传参
                this.name = name;
                this.age = age;
                this.score = score;//this代表实例化对象
            }
            exam(){//这是一个类方法,不要加function
                console.log('我叫'+this.name+'今年'+this.age+'岁这次考了'+this.score+'分')
            }
        }
        var pyq = new Student('pyq',18,0)
        
        pyq.exam() //我叫pyq今年18岁这次考了0分

猜你喜欢

转载自blog.csdn.net/qg2276879379/article/details/106914811