Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用对象进行封装(编程举例) #24

Open
zlluGitHub opened this issue May 5, 2018 · 0 comments
Open

使用对象进行封装(编程举例) #24

zlluGitHub opened this issue May 5, 2018 · 0 comments

Comments

@zlluGitHub
Copy link
Owner

zlluGitHub commented May 5, 2018

  • 例子

// 创建构造函数
function Dog() {
    this._init(option);
}
//创建共享属性。其中"_"表示转化成私有属性
Dog.prototype = {
    _init: function(option) {
        this.name = option.name;
        this.age = option.age;
        this.dogFrient = option.dogFrient;
    },
    eat: function(someThing) {
        console.log(this.name + '在吃' + someThing);
    },
    run: function(someThing) {
        console.log(this.name + '哪里' + someThing);
    }
}
  • 代码封装

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            width: 200px;
            height: 200px;
        }
    </style>
    <script>

        //使用函数将代码封装,使得复用性更高

        //使用函数封装带来的问题:
        //1.全局变量污染
        //2.代码结构不够清晰,维护不方便

        //使用对象进行封装后的优势
        //1.暴露在全局的只有一个对象名 不会造成全局变量污染
        //2.使用对象将代码进行功能模块的划分,有利于日后的维护

        window.onload = function () {

            var divs = itcastQuery.tag("div");
            itcastQuery.setStyle(divs);

            var ps = itcastQuery.tag("p");
            itcastQuery.setStyle(ps);
        }
        var itcastQuery = {
            //获取dom元素的方法们
            getEle:{
                tag: function (tagName){
                    return document.getElementsByTagName(tagName);
                },
                id: function (id){
                    return document.getElementById(id);
                }
                //通过classname获取元素的方法
                //....
            },
            //设置样式的方法们
            setCss: {
                setStyle: function (elements){
                    for (var j = 0; j < elements.length; j++) {
                        var ele = elements[j];
                        ele.style.border = "1px solid red";
                    }
                },
                css:function(option){},
                addClass:function(){},
                //..
            }
            //事件处理模块

        }
    </script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<p>我是第1个p元素</p>
<p>我是第2个p元素</p>
<p>我是第3个p元素</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant