美文网首页
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-继承方式二

    继承方式二的弊端如果动态的给Person的原型对象添加一个方法, 那么使用继承方式二就不能在子对象中访问say方法...

  • 原型继承

    原型链的继承 1.第一种继承方式(原型链继承) 2.第二种继承方式(第二种继承方式) 3.第三种继承方式(组合继承)

  • 前端 | JS | 面试中不得不知道的JS 继承的五种方式

    目录: JS中继承的概念 为什么要使用继承? 继承的第一种方式:原型链继承1 继承的第二种方式:原型链继承2 继承...

  • 今日份 小画

    -68-

  • 继承与闭包

    继承 继承是指一个对象直接使用另一对象的属性和方法。 继承的方式一 继承方式二对象冒充: call,apply方式...

  • js的继承方式

    js的继承方式 一、原型链继承 原型继承的缺点: 二. 构造函数继承 构造函数继承的缺点: 三. 组合式继承 组合...

  • javascript继承的等价模块化写法

    写法一: 写法二: 写法三: 继承: 调用方式:

  • 2021-01-26

    实现多线程的方式到底有几种?1.如何创建多线程方式一:继承Thread类方式二:实现Runnable接口继承Thr...

  • 多线程(二):实现多线程的两种方式

    一,多线程的实现方式 方式一: 继承Thread类 方式二: 实现Runable接口(推荐) 二,两种方式的区别 ...

  • Swift学习之字典转模型

    一、方式一: 二、方式二 setValuesForKeys属于oc的接口,因此必须继承NSObject。变量名称前...

网友评论

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

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