ES5物件導向基礎結構

weixin_30788239發表於2020-04-05
<!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>

 備註:文中多數內容摘自阮一峰老師文章,僅供自我學習查閱。

轉載於:https://www.cnblogs.com/xingxingclassroom/p/10386972.html

相關文章