构造函数 “对象冒充继承“和 “call apply bind“

91 阅读1分钟

 这种继承方法 使用了call apply bind能够修改this指向的特点 进行了对象冒充 但是这种方法 子类无法获取父类的原型上的属性和方法

实现构造函数2 继承构造函数1的属性和方法

     // 构造函数1
        function Game(name, type) {
            this.name = name
            this.gameType = type
            this.say = function() {
                console.log('欢迎来到' + this.name);
            }
            this.run = function() {
                console.log(1);
            }
        }
// 构造函数2  2继承1
        function Role(roleName, age, sex) {
            this.roleName = roleName
            this.age = age
            this.sex = sex
            this.dance = function() {
                console.log(`我是${this.roleName},今年${this.age}了,我是${this.sex}性`);
            };
            //实现继承构造函数1的属性和方法
            console.log(this); //是 Role 当前对象

            //1. bind方法需要小括号来调用第一个小括号参数是:函数上下文的对象,第二个小括号调用里面是参数列表,
            // Game.bind(this)('王者荣耀', '手游')

            //2.  call 方法第一个参数:第一个是作为函数上下文的对象,但是后面传入的是一个参数列表,而不是单个数组。
            // Game.call(this, '王者荣耀', '手游')

            //3. apply方法传入两个参数:第一个是函数上下文的对象,第二个是一个作为函数参数所组成的数组
            Game.apply(this, ['王者荣耀', '手游'])

        }
        let role = new Role('李白', '17', '男'); //实例一个对象 new创建传参
        console.log(role); //所有属性
        role.say(); //继承了Game的say方法
        role.dance(); //实例过后才可以调方法和属性
        role.run();

效果图