码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript-04-JS产生对象以及批量产生对象

时间:2018-12-31 20:21:56      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:[]   friends   构造   text   height   style   new   属性   func   

1.1创建对象

    <script text="text/javascript">
        //1.创建对象
        //this this 所在的函数属于哪个对象,this就代表这个对象
        //1.1直接创建
        var dog = {
            name: San,
            age: 18,
            height: 1.55,
            dogFriends: [Bob,Lili],
            eat:function (someThing) {
                console.log( this.name + + someThing);
            },
            run:function (someWhere) {
                console.log(this.name + + someWhere);
            }
        };//object
        console.log(typeof dog);

        //1.2输出这只狗对象的属性和行为
        console.log(dog.age,dog.dogFriends);
        dog.eat();
        dog.run(健身房);
    </script>

2.通过构造函数批量产生对象

    <script type="text/javascript">
        //通过构造函数批量产生对象
        //普通函数->构造函数
        var Dog = function () {
            console.log(这是一个普通函数);
        };
        //普通调用
        Dog();

        // alloc init -> new
        var dog1 = new Dog();
        var dog2 = new Dog();
        console.log(dog1,dog2);

    </script>

3.验证批量产生对象

     <script type="text/javascript">
        //创建构造函数 -> 抽象
        var Dog = function () {
            this.name = null;
            this.age = null;
            this.dogFriends = [];
            this.height = null;
            this.eat = function (someThing) {
                console.log(this.name +  + someThing);
            }
            this.run = function (someWhere) {
                console.log(this.name +  + someWhere);
            }
        }
        //批量产生对象
        var dog1 = new Dog();
        dog1.name = Peter;
        dog1.age = 15;
        dog1.dogFriends = [A,B];
        var dog2 = new Dog();
        dog2.name = Bob;
        dog2.age = 18;
        dog2.dogFriends = [C,D];
        console.log(dog1,dog2);

        //创建构造函数 -> 抽象
        var Dog1 = function (name,age,dogFriends,height) {
            this.name = name;
            this.age = age;
            this.dogFriends = dogFriends;
            this.height = height;
            this.eat = function (someThing) {
                console.log(this.name +  + someThing);
            }
            this.run = function (someWhere) {
                console.log(this.name +  + someWhere);
            }
        }
        var dog3 = new Dog1(Peter,15,[A,B],1);
        console.log(dog3);
    </script>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

JavaScript-04-JS产生对象以及批量产生对象

标签:[]   friends   构造   text   height   style   new   属性   func   

原文地址:https://www.cnblogs.com/StevenHuSir/p/10203091.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!