JS的对象

2016-10-05  本文已影响16人  Z了个L

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS的对象</title>
    <script>
        // this所在的函数在哪个对象中,this就代表这个对象
        // 对象
        var dog = {
            name: 'wangCai',
            age: 18,
            height: 166,
            dogFriends: ['laiFu', 'aHuang'],
            run: function (someWhere) {
               console.log(this.name + '在跑----' + someWhere);
            },
            eat: function (someThing) {
               console.log(this.name + '在吃----' + someThing);
            }
        };

        console.log(dog.name, dog.dogFriends);
        dog.run('杭州下沙');
        dog.eat('五花肉');

    </script>
</head>
<body>

</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script>
        function Dog() {
           console.log('我是一个普通函数');
        }

        // 调用函数
//        Dog();

        // 升级 ---> 构造函数 alloc init  new
        var dog1 = new Dog();
        var dog2 = new Dog();

        console.log(dog1, dog2);

    </script>
</head>
<body>

</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证批量产生对象</title>
    <script>
        // 构造函数
        function Dog() {
            this.name = null;
            this.age = null;
            this.height = null;
            this.dogFriends = [];
            this.eat = function (someThing) {
                console.log(this.name + '吃' + someThing);
            };
            this.run = function (someWhere) {
                console.log(this.name + '跑' + someWhere);
            }
        }

        // 产生对象
        var dog1 = new Dog();
        var dog2 = new Dog();

        dog1.name = 'lili';
        dog1.age = 18;
        dog1.dogFriends = ['232', '007'];


        dog2.name ='wangcai';
        dog2.age = 1;
        dog2.height = 0.22;

        console.log(dog1, dog2);

        dog1.eat('骨头');

        dog2.eat('奶');


        // 带参数
        function OtherDog(name, age, height, dogFriends) {
            this.name = name;
            this.age = age;
            this.height = height;
            this.dogFriends = dogFriends;
            this.eat = function (someThing) {
                console.log(this.name + '吃' + someThing);
            };
            this.run = function (someWhere) {
                console.log(this.name + '跑' + someWhere);
            }
        }

        var dog3 = new OtherDog('w', 19, 1122, ['2121']);

        console.log(dog3);
    </script>
</head>
<body>

</body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读