ES5面向对象基础结构

<!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>ES5面向对象</title>
</head>
<body>
    <script>
        function Test(name,age){//父类
            this.name = name;//配置参数
            this.age = age;
        }

        Test.getClassName = function(){//静态方法
            return 'Test';
        }

        Test.prototype.setName = function(name){//原型方法
            this.name = name;
        }

        Test.prototype.setAge = function(age){//原型方法
            this.age = age;
        }

        Object.defineProperties(Test.prototype,{//原型上添加或修改属性
            info:{
                get:function(){
                    return this.name + this.age;
                }
            },
            job: {
                value: '前端工程师',
                configurable: false,
                writable: true,
                enumerable: true
            },            
        });

        var t1 = new Test('Test',123);
        console.log(t1);//Test {name: "Test", age: 123}

        function NextTest(name,age,num){//子类
            Test.call(this,name,age);//继承配置参数
            this.num = num;
        }

        NextTest.__proto__ = Test;//继承静态方法

        NextTest.prototype = Text.prototype;//继承原型方法

        NextTest.prototype.setNum = function(num){//子类添加新的原型方法
            this.num = num;
        }

        var n1 = new NextTest('NextText',111,123456789);
        console.log(n1);//NextTest {name: "NextText", age: 111, num: 123456789}

    </script>
</body>
</html>

 

上一篇:微信小程序爬坑日记


下一篇:ES5和ES6类与继承的区别联系