javaScript——对象字面量模式、工厂模式

一、对象字面量模式:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>对象字面量模式</title>

    <!--事先知道对象的内容有哪些-->
    <script type="text/javascript">
        var p = {name:"李四",age:21,setName:function(name) {
            this.name = name;
        }};
        p.setName("修改后的名字");
        console.log(p.name+","+p.age);
    </script>
</head>
<body>
</body>
</html>

二、工厂模式:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>工厂模式</title>
    <script type="text/javascript">
        function creatPerson(name,age) {
            var obj = {
                name:name,
                age:age,
                setName:function(name){
                    this.name = name;
                }
            };
            return obj;
        }
        var p1 = creatPerson("你是",13);
        var p2 = creatPerson("猪吗",10);
        console.log(p1.name+","+p1.age);
        console.log(p2.name+","+p2.age);
    </script>
</head>
<body>
</body>
</html>

阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页