构造函数

116 阅读2分钟
<script>

        // 构造函数:用来构造一个实例的函数。

        // 风格:函数名首字母大写。 函数中一般没有返回值。

        // 使用场景:JS内置对象不够用的时候,我们可以自己定义一个类。
        
        // 构造函数:一个抽象对象 (一类对象)。
        // 创建
        function Person(name,age){
            // 定义属性,this指向实例化对象
            this.name = name;
            this.age = age;
            // 定义方法 (行为):函数表达式
            this.sayHi = function () {  
                console.log(`hi , my name is ${this.name} !`);
            };
            this.run = function (num) {  
                console.log(this.name + '每天跑' + num + '公里');
            };
        };
        // 3.实例化构造函数,new关键字“JS内置的关键字,表示实例化一个对象”。
        var lisa = new Person('LISA',18);
        console.log(lisa); //Person 对象
        lisa.sayHi();
        lisa.run(5);

        var tom = new Person('TOM',20);
        console.log(tom);
        tom.sayHi();
        tom.run(10);

原理 不使用new 此处伪程序,实现显性添加

function Test2() {  
            // 创建的this变量,指向空对象
            var this1 = {};
            this1.num = 100;
            this1.add = function (n) {  
                return this1.num + n;
            };
            // 返回this对象
            return this1;
        };
        var res2 = new Test2();
        console.log(res2);

构造函数误区(不使用new)

// 在构造函数中一般不使用return返回值。

// 构造函数执行过程中的最后一步是默认返回this。

// 每一个数据类型/构造函数  都有一个prototype属性,这个属性是用来存放公共的属性和方法的
function Person(name) {

            // 定义的属性和 方法  都是私有的

            this.name = name;  // this指向谁   实例对象

        }
// 公共的?  Person.prototype 构造函数的原型对象

        Person.prototype.type = '人';

// new 到底干了啥?

        var p3 = {};

        // call(p3, x1, x2, x3)  apply(p3, [x1, x2, x3])

        Person.call(p3, '李四');  // 更改this指向   继承私有的属性和方法

构造函数继承

function Animal() {
            // 私有的
            this.video = '啦啦啦啦'
        }
        // 公共的
        Animal.prototype.type = '动物';
        Animal.prototype.say = function() {
            console.log(this.video);
        }
        function Cat() {
            Animal.call(this);  // 将Animal的私有属性和方法都继承过来
            this.video = '喵喵喵';
        }
        Cat.prototype.footer = 4;
        // Cat.prototype和Animal.prototype父级一样 让 Cat.prototype多一个父级 Animal.prototype的父级就是  Cat.prototype的祖级
        Cat.prototype.__proto__ = Animal.prototype;  // Cat继承Animal公共的属性和方法
        var c = new Cat();
        console.log(c, c.footer, c.type);
        c.say();