<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <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);
                this.x = x;
                this.y = y;
            }
            substract() {
                console.log(this.x-this.y)
            }
        }
        var son1 = new Son(5,3)
        son1.substract()
        son1.sum()
    </script>
</body>
</html>

ES6之前没有类,通过构造函数模拟类

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function Star(uname,age) {
            this.uname = uname;
            this.age = age;
            this.sing = function() {
                console.log('我会唱歌')
            }
        }
        var ldh = new Star('刘德华',19)
        var zxy = new Star('张学友',23)
        console.log(ldh);
        ldh.sing();
        zxy.sing();
    </script>
</body>
</html>

实例成员就是带this的成员,只能通过实例化对象访问

静态成员只能通过构造函数访问

但是构造函数存在浪费内存的问题,所以引入原型对象prototype的概念,实现方法共享

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        function Star(uname,age) {
            this.uname = uname;
            this.age = age;
           
            }
        }
        Star.prototype.sing = function() {
            consloe.log('我会唱歌')
        }
        var ldh = new Star('刘德华',19)
        var zxy = new Star('张学友',23)
        ldh.sing();
        zxy.sing();
    </script>
</body>
</html>

 

原型链

posted on 2020-07-30 10:16  知否知否,  阅读(105)  评论(0编辑  收藏  举报