时间的法外狂徒

导航

JavaScript创建一个对象的方式

一、使用构造函数的方式

    <script>
        //通过构造函数创建对象
        function Person(name,age){
            this.name = name;
            this.age = age;
            this.do = function (){
               return "ok";
            }
        }
        var PerConstruction = new Person("feng",44);
        document.write("构造函数创建对象: "+PerConstruction.do()+"<br/>"); //页面加载完成后执行,页面内容将被覆盖。
</script>

二、通过对象字面量创建

    <script>
        //通过对象字面量创建对象
        var personJson = {
            name : "feng",
            age : 12,
            do : function (){

                return this.name;
            }
        }
        document.write("字面量创建对象:"+personJson.do()+"<br/>");
    </script>

三、通过内置Object对象

    <script>
        //通过内置的Object对象创建
        var personObject = new Object();
        personObject.name = "can";
        personObject.age = 99;
        personObject.do = function (msg){
            return "还你一个:"+msg;
        }

        document.write("内置Object对象创建:"+personObject.do("xiaotianji")+"<br/>");
    </script>

四、整体测试代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>js演示</title>
</head>
<body>
    <div >创建对象</div>
    <script>
        //通过内置的Object对象创建
        var personObject = new Object();
        personObject.name = "can";
        personObject.age = 99;
        personObject.do = function (msg){
            return "还你一个:"+msg;
        }

        document.write("内置Object对象创建:"+personObject.do("xiaotianji")+"<br/>");
    </script>
    <script>
        //通过对象字面量创建对象
        var personJson = {
            name : "feng",
            age : 12,
            do : function (){

                return this.name;
            }
        }
        document.write("字面量创建对象:"+personJson.do()+"<br/>");
    </script>
    <script>
        //通过构造函数创建对象
        function Person(name,age){
            this.name = name;
            this.age = age;
            this.do = function (){
               return "ok";
            }
        }
        var PerConstruction = new Person("feng",44);
        document.write("构造函数创建对象: "+PerConstruction.do()+"<br/>"); //页面加载完成后执行,页面内容将被覆盖。

        window.onload = function (){
            //document.write("是否覆盖");
        };
    </script>
</body>
</html>

 

posted on 2020-09-17 16:19  抄手砚  阅读(290)  评论(0编辑  收藏  举报