zoukankan      html  css  js  c++  java
  • js进阶写法 对象包含方法、数据及调用方式

    刚开始写js的时候到之后很长的一段时间,js代码都是比较凌乱的,看起来零零乱乱很是苦恼,于是就在想自己什么时候才能写出比较好看的代码呐,所以纪实一篇,以作心灵上的终结。

    var tvPlayFun = {
        init:function () {
            tvPlayFun.callFun();
        },
        callFun:function () {
            tvPlayFun.menuJudgeLoginFun();//用户是否登录
            mui('#offCanvasContentScroll').scroll();//主页面滚动
        },
        menuJudgeLoginFun:function () {
            if (1) {
                var tvUserList = document.querySelectorAll(".tvUserList")[0];
                tvUserList.children[1].style.display = "none";
                tvUserList.children[2].style.display = "none";
                tvUserList.children[3].style.display = "none";
            } else {
                // 登录代码
            }
        }
    }
    tvPlayFun.init();

    由以上代码可以看到,我们只需要创建一个对象变量,然后以键值对的形式创建函数就好了,而且可以根据具体要求,一种功能对应一个函数,然后根据要求在不同的函数里调用别的函数,既看起来美观好看,又对日后的维护起到了很大的方便,最重要的是,只要写得好,一个js文件夹里所有的函数就可能都只会写在这一个大的对象变量里,到时候看起来,多舒坦,多舒畅。

    另外,还可以继续在对象方法里面添加自己的对象变量,继续在里面添加对应的对象方法,看起来层层嵌套,很是优美,如果想要调用数据,还可以再对象变量里面添加对象,在里面放置数据,代码如下:

    var searchpage = {
        data:{
            searchBarInput:document.querySelectorAll(".searchBarInput")[0],
            searchConDel:document.querySelectorAll(".searchConDel")[0],
            say:"hello world"
        },
        init:function () {
            searchpage.callFun();
        },
        callFun:function () {
            window.onload = searchpage.onloadFun();
            searchpage.grandfatherFun();
        },
        onloadFun:function () {
            searchpage.data.searchBarInput.focus();
            console.log(searchpage.data.say);
            // 计算历史搜索框高度
            $(".historialSearchList").height($(window).height()-$(".searchBar").height()-$(".hotWords").height()-$(".historialSearchTitle").height()-$(".historialSearch").css("margin-top").replace("px",""));
        },
        grandfatherFun:function () {
            var fatherFun = {
                bigsonFun:function () {
                    console.log("我是大儿子");
                    fatherFun.middlesonFun();
                },
                middlesonFun:function () {
                    console.log("我是二儿子");
                    fatherFun.smallsonFun();
                },
                smallsonFun:function () {
                    console.log("我是小儿子");
                }
            }
            fatherFun.bigsonFun();
        }
    }
    searchpage.init();

    由以上代码中的onloadFun()方法中的console.log()可以得到专门存储数据的data对象里的say属性的内容,由grandfatherFun进一步印证层层嵌套的方法,可粘贴复制下来查看控制台输出,把不用的代码注释掉就好,完美结束。

    转载请注明出处!=>> http://www.cnblogs.com/zxn-9588/p/8663271.html

  • 相关阅读:
    R语言中的logical(0)和numeric(0)以及赋值问题
    创建hadoop用户
    虚拟机安装
    spark1-MapReduce
    arcgis1-shp转成mdb
    Actor-配置Maven
    scala6-单词计数(map(),flatMap())
    scala5-数组
    scala4-函数
    scala3-for循环
  • 原文地址:https://www.cnblogs.com/zxn-9588/p/8663271.html
Copyright © 2011-2022 走看看