关于JavaScript-继承属性的应用,extends call prototype

extends用法演示 

复制代码
<script>
        class Father{
            constructor(x, y){
                this.x = x;
                this.y = y;
            }
            sum(){
                console.log(this.x + this.y)
            }
        }

        class Son extends Father{
            constructor(x, y){
                super(x,y);  // 调用了父类中的构造函数
            }
        }
        var son = new Son(1,2);
        var son1 = new Son(11,22);

        son.sum();
        son1.sum();
    </script>
复制代码
Father构造的方法,子类使用extends能够继承父类的方法, 子类使用super即可调用.


call的使用
复制代码
<script>
        function fn(x, y){
            console.log('我想喝手磨咖啡');
            console.log(this);
            console.log(x + y);
        }

        var o = {
            name: 'andy'
        };

        // call第一个函数用于改变指向
        fn.call(o, 1, 2);


        function Star(role, age) {
            this.role = role;
            this.age = age;
        }

        var son = new Star('李白', 18)
        console.log(son.role);
        console.log(Star.role);
    </script>
复制代码

 

输出结果  :

我想喝手磨咖啡
Objectname: "andy"[[Prototype]]: Object
3
李白
undefined

 

call第一个参数能够改变this的指向

 

复制代码
<script>
        // 借用父构造函数继承属性
        // 1.父构造函数
        function Father(uname, age){
            // this 
            this.uname = uname;
            this.age = age;
        }

        Father.prototype.money = function(){
            console.log(100000);
        }


        function Son(uname, age, score){
            Father.call(this, uname, age);
            this.score = score;
        }

        // Son利用prototype指向Father 及Son拥有了父类的所有属性
        Son.prototype = new Father();
        // 对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数
        Son.prototype.constructor = Son;
        // 子构造函数专门的方法,由于Son在继承父类的属性后,给自己增加exam方法,所以父类是访问不到exam的
        Son.prototype.exam = function() {
            console.log('孩子考试');
        }

        var son = new Son('刘德华', 18, 100);
        console.log(son);
        console.log(Father.money);
        console.log(Son.prototype.constructor);
        console.log(son.exam());
        console.log(Son.prototype.exam());
        console.log(Father.prototype);
        console.log(Son.prototype);

    </script>
复制代码

 

posted @   一杯咖啡钱  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示