• js对象的继承以及公有私有属性的定义和读写


    最近想写一些js工具,有些方面需要用到面向对象的方法,比如继承父类属性和方法、通过私有化隐藏某些对象的属性等,因为没有系统的学习js,所以不知道怎么做,觉得很伤脑筋。

    今天受到技术群里朋友的提示,并查阅了一些资料,终于把这个问题解决了,真是大快人心啊,哈哈,哈哈,哈哈哈哈!!!

    下面列举了两种继承方式,各有优缺点,可根据业务需要选择,现把自己调试的代码整理如下,以备参考:

        <script type="text/javascript">
            function TestClassA(name, number) {
                this.name = name;             //public
                this.number = number;         //public
    
                var account = '';             //private
                var phone = '13612345678';    //private
                
                this.getAccount = function() {
                    return account;
                }
                this.setAccount = function (a) {
                    account = a;
                }
            }
    
            /* 类型继承(没有继承原型,且难以多重继承)
            // 1. 定义即继承(固定不变的继承) 
            function TestClassB(x, y) { 
                this.info = 'name:' + x + ', number:' + y; 
     
                //通过调用父类构造方法继承属性 
                TestClassA.call(this, x, y); 
            } 
            //创建实例 
            var b = new TestClassB("test name", 123); 
            //验证
            console.log(b);
    
    
            // 2. 使用时继承(灵活多变的继承)  
            function TestClassB(p, x, y) {
                this.info = 'name:' + x + ', number:' + y;
    
                //通过调用传入的类的构造方法继承属性  
                p.call(this, x, y);
            }
            //创建实例  
            var b = new TestClassB(TestClassA, "test name", 123);
            //验证
            console.log(b);
            */
    
            // 原型链继承(继承原型,方便多重继承)
            function TestClassB(p, x, y) {
                this.info = 'name:' + x + ', number:' + y;
            }
            TestClassB.prototype = new TestClassA();
            function TestClassC(p, x, y) {
                this.Msg = 'msg';
            }
            TestClassC.prototype = new TestClassB();
            //创建实例
            var c = new TestClassC("test c name", 456);
            c.setAccount("test account");
            console.log(c);
        </script>


  • 相关阅读:
    ReentrantLock 非公平锁不公平在哪
    spring 初始化Bean
    spring 循环引用问题,在一次问题调试过程中发现有个小伙伴竟然把循环引用设置成false了。估计是百度的时候没小心额外的代码吧。。。
    Maya2019下载安装与激活
    Maya2014下载安装与激活
    Maya2017下载安装与激活
    Windows 好用的护眼软件
    万兴全能格式转换器_11.2.0.232 下载安装和激活
    处理视频相关的软件
    几款好用的录屏软件推荐
  • 原文地址:https://www.cnblogs.com/foren/p/6009071.html
Copyright © 2020-2023  润新知