主頁 > 企業開發 > JS的原型和繼承,讓javascript功力再上一層

JS的原型和繼承,讓javascript功力再上一層

2020-11-24 23:24:02 企業開發

    <script>
        'use strict';

        // let arr = [1, 2, 3];
        // let res = arr.concat(5, 6);
        // console.log(res);
        // 原型鏈
        // __proto__ 上一級原型 Array(0)
        // __proto__ 上上一級原型 Object


        let obj1 = {};
        console.log(obj1);// __proto__ 上一級原型 Object


        // 獲取原型
        let proto1 = Object.getPrototypeOf(obj1);
        console.log(obj1);


        let obj2 = { name: 'cyy' };
        let proto2 = Object.getPrototypeOf(obj2);
        console.log(proto1 == proto2);
    </script>

 

沒有原型的物件也是存在的:

    <script>
        'use strict';

        //Object.create 指定原型和屬性
        // 完全的資料字典物件
        let obj = Object.create(null, {
            name: {
                value: 'cyy'
            }
        });
        console.log(obj);
        //hasOwnProperty是原型的方法,由于obj沒有原型,因為無法使用該方法
        console.log(obj.hasOwnProperty('name'));
    </script>

 

原型方法與物件方法的優先級:

    <script>
        'use strict';

        //自己有就執行自己的,自己沒有就執行原型的,原型也沒有就沒法執行

        
        // let obj = {
        //     show() {
        //         console.log('obj.show');
        //     }
        // }
        // obj.__proto__.show = function () {
        //     console.log('obj.__proto__.show');
        // }
        // obj.show();


        let obj = {}
        obj.__proto__.show = function () {
            console.log('obj.__proto__.show');
        }
        obj.show();
    </script>

 

函式擁有多個長輩:

1.每個物件都具有一個名為__proto__的屬性;

2.每個建構式(建構式標準為大寫開頭,如Function(),Object()等等JS中自帶的建構式,以及自己創建的)都具有一個名為prototype的方法(注意:既然是方法,那么就是一個物件(JS中函式同樣是物件),所以prototype同樣帶有__proto__屬性);

3.每個物件的__proto__屬性指向自身建構式的prototype;

    <script>
        'use strict';

        // function user() { }
        // // 列印結果
        // console.log(user);
        // // 列印詳細結構
        // console.dir(user);


        // prototype和__proto__都是原型,但是使用場景不一樣
        // prototype是建構式的,__proto__是物件的
        function User() { }
        let obj = new User();
        console.log(obj.__proto__ == User.prototype);

    </script>

 

原型關系詳解與屬性繼承實體:

    <script>
        'use strict';

        // 系統常見建構式 Number String Function Object
        let obj = new Object();
        obj.name = 'cyy';
        // console.dir(obj);// 物件有__proto__屬性,沒有prototype屬性


        Object.prototype.show = function () {
            console.log('Object-prototype-show');
        }
        // console.dir(Object);// 系統建構式Object有__proto__屬性和prototype屬性


        // Object.prototype的原型為null
        // console.dir(Object.prototype.__proto__);


        function User() { }
        //建構式User有__proto__屬性和prototype屬性
        console.dir(User);
        console.log(User.__proto__.__proto__ == User.prototype.__proto__);


        let u = new User();
        u.show();


        User.show();
    </script>

 

系統建構式的原型體現:

    <script>
        'use strict';

        // let obj = {};
        // console.log(obj.__proto__ == Object.prototype);


        let arr = [];
        console.log(arr.__proto__ == Array.prototype);
        Array.prototype.show = function () {
            console.log('show');
        }
        arr.show();


        // let str = '111';
        // console.log(str.__proto__ == String.prototype);


        // let bool = true;
        // console.log(bool.__proto__ == Boolean.prototype);


        // let reg = /a/i; //new RegExp
        // console.log(reg.__proto__ == RegExp.prototype);
    </script>

 

自定義物件的原型設定:

    <script>
        'use strict';

        let child = { name: 'child' };
        let parent = {
            name: 'parent', show() {
                console.log('show:' + this.name);
            }
        };
        console.log(child.__proto__ == Object.prototype);


        // 設定原型
        Object.setPrototypeOf(child, parent);
        child.show();


        // 獲取原型
        console.log(Object.getPrototypeOf(child));
    </script>

 

原型中的constructor參考:

 

    <script>
        function User(name) {
            this.name = name;
        }
        console.dir(User);
        // prototype是物件,物件的原型用__proto__獲取
        // 建構式通過prototype來找原型
        console.log(User.prototype.__proto__ == Object.prototype);
        console.log(User.__proto__.__proto__ == Object.prototype);
        // 原型通過constructor來找建構式
        console.log(User.prototype.constructor == User);
        let cyy = new User.prototype.constructor('cyy');
        console.log(cyy);
        // __proto__只服務于物件自己本身


        // 在prototype中加功能
        // User.prototype.show = function() {
        //     console.log(this.name);
        // }
        // cyy.show();


        // 同時添加多個功能
        User.prototype = {
            constructor: User,
            show1() {
                console.log('show1');
            },
            show2() {
                console.log('show2');
            }
        };
        let cyy2 = new User.prototype.constructor('cyy');
        console.log(cyy2);
        cyy2.show1();
        cyy2.show2();
    </script>

 

給我一個物件還你一個世界:

    <script>
        function User(name) {
            this.name = name;
            // this.show = function() {
            //     console.log(this.name);
            // }
        }
        let cyy = new User('cyy');
        // console.log(cyy);

        User.prototype = {
            constructor: User,
            show() {
                console.log(this.name);
            }
        };

        function createByObject(obj, ...args) {
            const constructor = Object.getPrototypeOf(obj).constructor; // 獲取指定物件的建構式
            // console.log(constructor == User);
            return new constructor(...args);
        }
        let cyy2 = createByObject(cyy, 'cyy的子物件');
        console.log(cyy2);
        cyy2.show();
    </script>

 

總結一下原型鏈:

    <script>
        // let arr = [];
        // // arr是物件,物件只有__proto__屬性
        // console.log(arr.__proto__ == Array.prototype);
        // console.log(arr.__proto__.__proto__ == Object.prototype);
        // console.log(Object.prototype.__proto__); //null


        let a = {
            name: 'a'
        };
        let c = {
            name: 'c'
        };
        let b = {
            name: 'b',
            show() {
                console.log(this.name)
            }
        };
        Object.setPrototypeOf(a, b); //a的原型設定為b
        console.log(a);
        a.show();

        Object.setPrototypeOf(c, b); //a的原型設定為b
        console.log(c);
        c.show();
    </script>

 

原型鏈檢測之instanceof:

    <script>
        function A() {}

        function B() {}

        function C() {}

        // 這里順序很重要,先修改A的原型,再實體化A
        let c = new C();
        B.prototype = c;
        let b = new B();
        A.prototype = b;
        let a = new A();

        // 檢測a的原型鏈上是否有A的prototype
        console.log(a instanceof A);
        console.log(a instanceof Object);
        console.log(a instanceof B);
        console.log(a instanceof C);
        console.log(b instanceof C);
    </script>

 

Object.isPortotypeOf 原型檢測:

    <script>
        let a = {};
        let b = {};
        let c = {};
        Object.setPrototypeOf(b, c);
        console.log(b.isPrototypeOf(a)); //b是否在a的原型鏈上
        console.log(b.__proto__ == Object.prototype);
        console.log(b.__proto__.isPrototypeOf(a));

        Object.setPrototypeOf(a, b);
        console.log(b.isPrototypeOf(a));
        console.log(c.isPrototypeOf(a));
        console.log(c.isPrototypeOf(b));
    </script>

 

in與hasOwnProperty的屬性差異:

        let a = {
            name: 'a'
        };
        let b = {
            age: 18
        };
        console.log('name' in a); //name屬性是否在a物件上,或者在a的原型鏈上
        console.log('web' in a);
        Object.prototype.web = 'url';
        console.log('web' in a);

        console.log(a.hasOwnProperty('name')); // 檢測a物件是否含有name屬性,不會去檢測原型鏈
        Object.setPrototypeOf(a, b);
        console.log('age' in a);
        console.log(a.hasOwnProperty('age'));

        for (const key in a) {
            // console.log(key);

            if (a.hasOwnProperty(key)) {
                console.log(key);
            }
        }

 

使用call或者apply借用原型鏈:

    <script>
        // let obj = {
        //     data: [11, 44, 2, 77, 2]
        // };
        // Object.setPrototypeOf(obj, {
        //     max() {
        //         return this.data.sort((a, b) => b - a)[0]; // 從大到小排序之后的陣列,最大值在第一位
        //     }
        // });
        // console.log(obj.max());

        // let lessonObj = {
        //     lessons: {
        //         html: 3,
        //         css: 58,
        //         js: 88
        //     },
        //     //getter
        //     get data() {
        //         return Object.values(this.lessons);
        //     }
        // };
        // let res = obj.max.apply(lessonObj); // 借用其他物件原型鏈中的方法
        // console.log(res);


        //沒有this引數的情況
        let obj = {
            data: [11, 44, 2, 77, 2]
        };
        Object.setPrototypeOf(obj, {
            max(data) {
                return data.sort((a, b) => b - a)[0]; // 從大到小排序之后的陣列,最大值在第一位
            }
        });
        console.log(obj.max(obj.data));

        let lessonObj = {
            lessons: {
                html: 3,
                css: 58,
                js: 88
            }
        };
        let res = obj.max.call(null, Object.values(lessonObj.lessons)); //沒有用到this,第一個引數可以設定為null
        console.log(res);
    </script>

 

優化方法借用:

    <script>
        // console.log(Math.max(22, 55, 33));

        // let obj = {
        //     data: [11, 44, 2, 77, 2]
        // };
        // console.log(Math.max.apply(null, obj.data));

        // let lessonObj = {
        //     lessons: {
        //         html: 3,
        //         css: 58,
        //         js: 88
        //     }
        // };
        // console.log(Math.max.apply(null, Object.values(lessonObj.lessons)));


        // 使用展開語法
        let arr = [22, 55, 33];
        console.log(Math.max(...arr));

        let obj = {
            data: [11, 44, 2, 77, 2]
        };
        console.log(Math.max.call(null, ...obj.data));

        let lessonObj = {
            lessons: {
                html: 3,
                css: 58,
                js: 88
            }
        };
        console.log(Math.max.call(null, ...Object.values(lessonObj.lessons)));
    </script>

 

DOM節點借用Array原型方法:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo</title>
</head>

<body>
    <button message="cyy1" class="red">cyy1</button>
    <button message="cyy2">cyy2</button>

    <script>
        //array的過濾操作
        let arr = [1, 2, 3, 4, 5];
        console.log(arr.filter(item => item > 3));
        console.dir(arr.__proto__.filter);
        console.dir(Array.prototype.filter);

        const btns = document.querySelectorAll('button');
        // let res = Array.prototype.filter.call(btns, btn => {
        //     // console.log(btn);
        //     return btn.hasAttribute('class');
        // });
        let res = [].filter.call(btns, btn => {
            // console.log(btn);
            return btn.hasAttribute('class');
        });
        console.log(res);
        console.log(res[0].innerHTML);
    </script>
</body>

</html>

 

合理的建構式方法宣告:

    <script>
        // function User(name) {
        //     this.name = name;
        //     this.show = function() {
        //         console.log(this.name);
        //     }
        // }
        // let cyy1 = new User('cyy1');
        // let cyy2 = new User('cyy2');
        // console.dir(cyy1);
        // console.dir(cyy2);
        //這里的show方法寫在建構式里面,存在記憶體浪費,可以組合使用建構式方法和原型方法


        // function User(name) {
        //     this.name = name;
        // }
        // User.prototype.show = function() {
        //     console.log(this.name);
        // }
        // let cyy1 = new User('cyy1');
        // let cyy2 = new User('cyy2');
        // console.dir(cyy1);
        // console.dir(cyy2);


        // 多個方法
        function User(name) {
            this.name = name;
        }
        User.prototype = {
            constructor: User,
            show() {
                console.log(this.name);
            }
        }
        let cyy1 = new User('cyy1');
        let cyy2 = new User('cyy2');
        console.dir(cyy1);
        console.dir(cyy2);
    </script>

 

this和原型沒有關系的:

this與原型無關,始終指向呼叫原型的物件 始終指向函式運行的背景關系
  不要濫用原型:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo</title>
</head>

<body>
    <button onclick="this.hide()">btn</button>

    <script>
        // 不建議在系統的原型中追加方法
        Object.prototype.hide = function() {
            // console.log('hide');
            this.style.display = 'none'; //this指向被點擊的button
        }
    </script>
</body>

</html>

 

Object.create與__proto__:

    <script>
        // 單個物件修改原型的方法
        let User = {
            show() {
                console.log(this.name);
            }
        }


        // 1、通過Object.create創建物件并指定原型
        // 缺點:只能定義原型,不能獲取
        // let cyy = Object.create(User, {
        //     name: {
        //         value: 'cyy'
        //     }
        // });
        // cyy.show();
        // console.log(cyy);

        // let cyy2 = Object.create(User);
        // cyy2.name = 'cyy2';
        // cyy2.show();


        // 2、使用__proto__,可以設定原型,也可以獲取原型
        let cyy = {
            name: 'cyy'
        };
        cyy.__proto__ = User;
        cyy.show();
        console.log(cyy.__proto__);
    </script>

 

使用setPrototypeOf替代__proto__:

    <script>
        // 單個物件修改原型的方法
        let User = {
            show() {
                console.log(this.name);
            }
        }

        // __proto__是非標準操作
        // setPrototypeOf()是標準操作

        // 推薦使用Object.setPrototypeOf定義原型,使用Object.getPrototypeOf獲取原型
        let cyy = {
            name: 'cyy'
        };
        Object.setPrototypeOf(cyy, User);
        cyy.show();
        console.dir(cyy);
        console.log(Object.getPrototypeOf(cyy));
    </script>

 

__proto__原來是屬性訪問器:

    <script>
        // __proto__ getter setter
        let User = {
            name: 'user'
        }
        User.__proto__ = {
            show() {
                console.log(this.name);
            }
        }
        User.show();
        console.log(User.__proto__);

        User.__proto__ = 99;
        // 智能判斷,如果是物件,則修改原型;否則不修改
        console.log(User.__proto__);


        let user = {
                action: {},
                get proto() {
                    return this.action;
                },
                set proto(obj) {
                    if (obj instanceof Object) {
                        this.action = obj;
                    }
                }
            }
            // let obj = 99;
            // user.proto = obj;
            // console.log(user.proto);

        let obj = {
            name: 'obj'
        };
        user.proto = obj;
        console.log(user.proto);


        let obj2 = {};
        console.dir(obj2);


        // 如何讓物件設定__proto__屬性為非物件?
        // 不繼承Object即可
        let obj3 = Object.create(null);
        obj3.__proto__ = 'obj3';
        console.log(obj3);
    </script>

 

改變建構式原型并不是繼承:

    <script>
        // 原型的繼承,而不是改變建構式的原型
        // function User() {
        //     this.name = function() {
        //         console.log('name method');
        //     }
        // }
        // let cyy = new User('cyy');
        // console.dir(cyy);


        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }
        let cyy = new User('cyy');
        console.dir(cyy);


        // 改變建構式的原型
        function Admin() {}
        Admin.prototype = User.prototype; // 這是賦值,而不是繼承,改變Admin的原型的同時,也改變了User的原型
        Admin.prototype.role = function() {
            console.log('admin role');
        }


        function Member() {}
        Member.prototype = User.prototype;
        Member.prototype.role = function() {
            console.log('member role');
        }
        let m = new Member();
        m.name();


        let a = new Admin();
        a.name();
        a.role();
    </script>

 

繼承是原型的繼承:

    <script>
        // let f = {};
        // console.dir(f.__proto__);
        // console.log(Object.getPrototypeOf(f)); //查看原型

        // 1、這種設定方式,對于順序沒有要求
        // 實作原型的繼承,保留本身的方法和屬性,不會被覆寫和互相影響
        // function User() {}
        // User.prototype.name = function() {
        //     console.log('User name');
        // }

        // // 改變建構式的原型
        // function Admin() {}
        // // Admin.prototype.__proto__指向Object.prototype,就是指向null
        // Admin.prototype.__proto__ = User.prototype; // 這是原型的繼承
        // Admin.prototype.role = function() {
        //     console.log('admin role');
        // }

        // function Member() {}
        // // Member.prototype.__proto__指向Object.prototype,就是指向null
        // Member.prototype.__proto__ = User.prototype; // 這是原型的繼承
        // Member.prototype.role = function() {
        //     console.log('member role');
        // }

        // let a = new Admin();
        // a.role();
        // let m = new Member();
        // m.role();


        // 2、這種設定方式,對順序有要求
        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }

        // 改變建構式的原型
        function Admin() {}
        Admin.prototype.role = function() { //這個role方法在原來的Admin原型物件上,修改后就沒有了
            console.log('admin role');
        }
        Admin.prototype = Object.create(User.prototype);

        function Member() {}
        Member.prototype.role = function() {
            console.log('member role');
        }
        Member.prototype = Object.create(User.prototype);

        let a = new Admin();
        a.role();
        let m = new Member();
        m.role();
    </script>

 

繼承對新增物件的影響:

    <script>
        // 1、這種設定方式,對于順序沒有要求
        // function User() {}
        // User.prototype.name = function() {
        //     console.log('User name');
        // }

        // // 改變建構式的原型
        // function Admin() {}
        // let a = new Admin();

        // // 改變原來原型物件的原型,就是Object.prototype的原型
        // Admin.prototype.__proto__ = User.prototype; 
        // Admin.prototype.role = function() {
        //     console.log('admin role');
        // }

        // a.role();



        // 2、這種設定方式,對順序有要求
        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }

        // 先實體化,再改變建構式的原型;此時物件不具有新的原型物件的方法
        function Admin() {}
        let a = new Admin();

        Admin.prototype = Object.create(User.prototype);
        Admin.prototype.role = function() { //這個role方法在原來的Admin原型物件上,修改后就沒有了
            console.log('admin role');
        }

        a.role();
    </script>

 

繼承對constructor屬性的影響:

    <script>
        // function User() {}
        // let obj1 = new User();
        // console.log(obj1.__proto__.constructor == User);
        // let obj2 = new obj1.__proto__.constructor;
        // console.log(obj2);


        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }

        // 先實體化,再改變建構式的原型;此時物件不具有新的原型物件的方法
        function Admin() {}

        Admin.prototype = Object.create(User.prototype); //這種方式指定原型,沒有constructor
        Admin.prototype.constructor = Admin; //手動指定constructor
        Admin.prototype.role = function() { //這個role方法在原來的Admin原型物件上,修改后就沒有了
            console.log('admin role');
        }

        let a = new Admin();
        console.log(a.__proto__);
        let b = new a.__proto__.constructor;
        console.log(b);
    </script>

 

禁止constructor被遍歷:

    <script>
        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }

        function Admin() {}

        Admin.prototype = Object.create(User.prototype); //這種方式指定原型,沒有constructor
        Object.defineProperty(Admin.prototype, 'constructor', {
            value: Admin,
            enumerable: false, //不允許遍歷
        });
        console.log(Object.getOwnPropertyDescriptors(Admin.prototype));

        Admin.prototype.role = function() {
            console.log('admin role');
        }

        let a = new Admin();
        for (const key in a) {
            console.log(key);
        }
    </script>

 

方法重寫與父級屬性訪問:

    <script>
        function User() {}
        User.prototype.name = function() {
            console.log('User name');
        }
        User.prototype.age = 18;

        function Admin() {}

        Admin.prototype = Object.create(User.prototype); //這種方式指定原型,沒有constructor
        Admin.prototype.constructor = Admin;
        Admin.prototype.role = function() {
                console.log('admin role');
            }
            // 重寫父類中的方法,并使用父類中的屬性
        Admin.prototype.name = function() {
            console.log(User.prototype.age + ' admin name');
        }

        let a = new Admin();
        a.name();
    </script>

 

面向物件的多型:

    <script>
        function User() {}
        User.prototype.show = function() {
            this.role(); //role方法在每個子物件中實作
        }

        function Admin() {}
        Admin.prototype = Object.create(User.prototype);
        Admin.prototype.role = function() {
            console.log('admin role');
        }

        function Member() {}
        Member.prototype = Object.create(User.prototype);
        Member.prototype.role = function() {
            console.log('member role');
        }

        for (const obj of[new Admin, new Member]) {
            obj.show();
        }
    </script>

 

使用父類建構式初始屬性:

    <script>
        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }

        function Admin(...args) {
            User.apply(this, args);
        }
        Admin.prototype = Object.create(User.prototype);

        function Member(name, age) {
            User.call(this, name, age);
        }
        Member.prototype = Object.create(User.prototype);

        let a = new Admin('admin', 18);
        let b = new Member('member', 20);
        a.show();
        b.show();
    </script>

 

使用原型工廠封裝繼承:

    <script>
        function extend(sub, sup) {
            sub.prototype = Object.create(sup.prototype);
            Object.defineProperty(sub.prototype, 'constructor', {
                value: sub,
                enumerable: false
            });
        };

        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }


        function Admin(...args) {
            User.apply(this, args);
        }
        extend(Admin, User);
        let admin = new Admin('cyy', 18);
        admin.show();


        function Member(name, age) {
            User.call(this, name, age);
        }
        extend(Member, User);
        let member = new Member('cyy2', 22);
        member.show();
    </script>

 

物件工廠派生物件并實作繼承:

    <script>
        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }


        function admin(name, age) {
            let instance = Object.create(User.prototype);
            User.call(instance, name, age);
            instance.info = function() {
                console.log('admin--info');
            }
            return instance;
        }
        let cyy1 = admin('cyy1', 11);
        cyy1.show();
        cyy1.info();
    </script>

 

多繼承造成的困擾:

 

    <script>
        function Request() {}
        Request.prototype.ajax = function() {
            console.log('請求后臺');
        }


        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype = Object.create(Request.prototype);
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }


        function admin(name, age) {
            let instance = Object.create(User.prototype);
            User.call(instance, name, age);
            instance.info = function() {
                console.log('admin--info');
            }
            return instance;
        }
        let cyy1 = admin('cyy1', 11);
        cyy1.ajax();
    </script>

 

使用mixin實作多繼承:

    <script>
        //改造成物件,把要繼承的方法變成物件的屬性
        let Request = {
            ajax() {
                console.log('請求后臺');
            }
        };


        let Credit = {
            all() {
                console.log('請求積分');
            }
        };


        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }


        function Admin(name, age) {
            User.call(this, name, age);
        }
        Admin.prototype = Object.create(User.prototype); // Admin繼承User

        // 陣列的合并實作多繼承
        Admin.prototype = Object.assign(Admin.prototype, Request, Credit);
        let cyy1 = new Admin('cyy1', 11);
        cyy1.ajax();
        cyy1.all();
    </script>

 

mixin的內部繼承與super關鍵字:

    <script>
        let obj = {};
        console.dir(obj);


        //改造成物件,把要繼承的方法變成物件的屬性
        let Request = {
            ajax() {
                return '請求后臺';
            }
        };


        let Credit = {
            __proto__: Request,
            all() {
                // console.log(this.__proto__.ajax() + '請求積分');
                // super 當前類的原型,super關鍵字也可以用來呼叫父物件上的函式
                console.log(super.ajax() + '請求積分');
            }
        };


        function User(name, age) {
            this.name = name;
            this.age = age;
        }
        User.prototype.show = function() {
            console.log(this.name + this.age);
        }


        function Admin(name, age) {
            User.call(this, name, age);
        }
        Admin.prototype = Object.create(User.prototype); // Admin繼承User

        // 陣列的合并實作多繼承
        Admin.prototype = Object.assign(Admin.prototype, Request, Credit);
        let cyy1 = new Admin('cyy1', 11);
        console.log(Admin);
        console.log(Credit);
        cyy1.ajax();
        cyy1.all();

    </script>

 

TAB選項卡顯示效果基類開發:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo</title>
    <style>
        main {
            position: relative;
            display: inline-block;
            margin-right: 100px;
            width: 200px;
            height: 200px;
        }
        
        nav>a {
            display: inline-block;
            padding: 10px 20px;
            background: orange;
            border: 1px solid #ddd;
        }
        
        section {
            width: 200px;
            height: 100px;
            background: pink;
            position: absolute;
            top: 50px;
        }
    </style>
</head>

<body>
    <main class="tab1">
        <nav>
            <a href="javascript:;">cyy1</a>
            <a href="javascript:;">cyy2</a>
        </nav>
        <section>1</section>
        <section>2</section>
    </main>

    <main class="tab2">
        <nav>
            <a href="javascript:;">cyy1</a>
            <a href="javascript:;">cyy2</a>
        </nav>
        <section>1</section>
        <section>2</section>
    </main>

    <script>
        // 原型工廠
        function extend(sub, sup) {
            sub.prototype = Object.create(sup.prototype);
            Object.defineProperty(sub.prototype, 'constructor', {
                value: sub,
                enumerable: false
            });
        }

        function Animation() {}
        Animation.prototype.show = function() {
            this.style.display = 'inline-block';
        }
        Animation.prototype.hide = function() {
            this.style.display = 'none';
        }
        Animation.prototype.background = function(color) {
            this.style.backgroundColor = color;
        }

        let tab = document.querySelector('.tab2');
        // Animation.prototype.hide.call(tab);
        Animation.prototype.background.call(tab, 'lightblue');

        function Tab(el) {
            this.tab = document.querySelector(el);
            // console.log(this.tab);
            this.links = this.tab.querySelectorAll('a');
            this.sections = this.tab.querySelectorAll('section');
            // console.log(this.sections);
        }
        extend(Tab, Animation);
        Tab.prototype.run = function() {
            this.reset();
            this.action(0);
            this.bindEvent();
        }
        Tab.prototype.bindEvent = function() {
            this.links.forEach((a, i) => {
                // 閉包
                a.addEventListener('click', () => {
                    this.action(i);
                });
            });
        }
        Tab.prototype.action = function(i) {
            this.reset();
            this.background.call(this.links[i], 'orange');
            this.show.call(this.sections[i]);
        }
        Tab.prototype.reset = function() {
            this.links.forEach((el, i) => {
                this.background.call(this.links[i], '#ddd');
            });
            this.sections.forEach((el, i) => {
                this.hide.call(this.sections[i]);
            });
        }

        new Tab('.tab1').run();
    </script>
</body>

</html>

 

 

開放更多API實作靈活定制:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo</title>
    <style>
        main {
            position: relative;
            display: inline-block;
            margin-right: 100px;
            width: 200px;
            height: 200px;
        }

        nav>a,
        nav>span {
            display: inline-block;
            padding: 10px 20px;
            background: orange;
            border: 1px solid #ddd;
        }

        section {
            width: 200px;
            height: 100px;
            background: pink;
            position: absolute;
            top: 50px;
        }
    </style>
</head>

<body>
    <main class="tab1">
        <nav>
            <span>cyy1</span>
            <span>cyy2</span>
        </nav>
        <section>1</section>
        <section>2</section>
    </main>

    <main class="tab2">
        <nav>
            <a href="javascript:;">cyy1</a>
            <a href="javascript:;">cyy2</a>
        </nav>
        <section>1</section>
        <section>2</section>
    </main>

    <script>
        // 原型工廠
        function extend(sub, sup) {
            sub.prototype = Object.create(sup.prototype);
            Object.defineProperty(sub.prototype, 'constructor', {
                value: sub,
                enumerable: false
            });
        }

        function Animation() { }
        Animation.prototype.show = function () {
            this.style.display = 'inline-block';
        }
        Animation.prototype.hide = function () {
            this.style.display = 'none';
        }
        Animation.prototype.background = function (color) {
            this.style.backgroundColor = color;
        }

        // let tab = document.querySelector('.tab2');
        // Animation.prototype.hide.call(tab);
        // Animation.prototype.background.call(tab, 'lightblue');

        function Tab(args) {
            args = Object.assign({
                el: null,
                link: 'a',
                section: 'section',
                callback: null
            }, args);
            this.tab = document.querySelector(args['el']);
            // console.log(this.tab);
            this.links = this.tab.querySelectorAll(args['link']);
            this.sections = this.tab.querySelectorAll(args['section']);
            // console.log(this.sections);
            this.callback = args['callback'];
        }
        extend(Tab, Animation);
        Tab.prototype.run = function () {
            this.reset();
            this.action(0);
            this.bindEvent();
        }
        Tab.prototype.bindEvent = function () {
            this.links.forEach((a, i) => {
                // 閉包
                a.addEventListener('click', () => {
                    this.action(i);
                });
                if (this.callback) this.callback();
            });
        }
        Tab.prototype.action = function (i) {
            this.reset();
            this.background.call(this.links[i], 'orange');
            this.show.call(this.sections[i]);
        }
        Tab.prototype.reset = function () {
            this.links.forEach((el, i) => {
                this.background.call(this.links[i], '#ddd');
            });
            this.sections.forEach((el, i) => {
                this.hide.call(this.sections[i]);
            });
        }

        new Tab({
            el: '.tab1',
            link: 'span',
            callback() {
                console.log('執行回呼');
            }
        }).run();

        new Tab({ el: '.tab2' }).run();
    </script>
</body>

</html>

 

 

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/227119.html

標籤:其他

上一篇:DOM事件流與事件物件

下一篇:單例模式

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more