美文网首页
68-继承方式二

68-继承方式二

作者: 仰望_IT | 来源:发表于2019-04-27 01:28 被阅读0次
            function Person(myName, myAge) {
                // let per = new Object();
                // let this = per;
                // this = stu;
                this.name = myName; // stu.name = myName;
                this.age = myAge;   // stu.age = myAge;
                this.say = function () {    // stu.say = function () {}
                    console.log(this.name, this.age);
                }
                // return this;
            }
            function Student(myName, myAge, myScore) {
                // let stu = new Object();
                // let this = stu;
    
                // 通过call修改this和传参
                Person.call(this, myName, myAge); // Person.call(stu);
                this.score = myScore;
                this.study = function () {
                    console.log("day day up");
                }
                // return this;
            }
            let stu = new Student("ww", 19, 99);
    
            console.log(stu.score);  // 99
            stu.say();  // ww 19
            stu.study();  // day day up
    
    • 继承方式二的弊端
      • 如果动态的给Person的原型对象添加一个方法, 那么使用继承方式二就不能在子对象中访问say方法

            function Person(myName, myAge) {
                // let per = new Object();
                // let this = per;
                // this = stu;
                this.name = myName; // stu.name = myName;
                this.age = myAge;   // stu.age = myAge;
                // return this;
            }
        
            // 如果将say方法放到Person原型对象中, 那么用继承方式二将不能访问say, 这就是继承方式二的弊端
            Person.prototype.say = function () {
                console.log(this.name, this.age);
            }
        
            function Student(myName, myAge, myScore) {
                // let stu = new Object();
                // let this = stu;
                Person.call(this, myName, myAge); // Person.call(stu);
                this.score = myScore;
                this.study = function () {
                    console.log("day day up");
                }
                // return this;
            }
        
            let stu = new Student("ww", 19, 99);
            console.log(stu.score);
            stu.say();  // 报错
            stu.study();
        
        报错的原因

    相关文章

      网友评论

          本文标题:68-继承方式二

          本文链接:https://www.haomeiwen.com/subject/ruthnqtx.html