javascript对象、原型

2016-10-26  本文已影响110人  该帐号已被查封_才怪

一、问答

(一 )、OOP 指什么?有哪些特性

指的是面向对象编程,(全称是Object Oriented Programming,OOP),它是一种计算机编程架构。面向对象程序设计可以看作一种在程序中包含各种独立而又互相调用的对象的思想。它具有如下特性:
1、封装性;
2、继承性;
3、多态性;
4、抽象性;

(二 )、如何通过构造函数的方式创建一个拥有属性和方法的对象?

可通过如下形式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>trigger</title>
</head>
<body>

    <button class="btn">trigger</button>

    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>

        // $(".btn").on("click",function(){
        //  var i=0;
        //  i++;
        //  console.log(i)
        // })

        // setInterval (function(){
        //  $(".btn").trigger("click")
        // },2000)

        function People(name,age){
            this.name=name;
            this.age=age;
            console.log("我是: "+this.name+",我的年龄是:"+this.age)            
        }

        People.prototype.sayName=function(){
            console.log("hello")
        }

        var p1=new People("licai",24),
        p2=new People("zhangsan",20);

    </script>

</body>
</html>
Paste_Image.png
(三 )、prototype 是什么?有什么特性?

每个函数都有一个prototype属性,prototype里默认有两个属性一个是constructor,另一个是__proto__ (不同浏览器命名可能不同),constructor其实指向该函数本身,而__proto__ 则指向window下的Object.prototype,也就是说该函数的创建者是Object People.prototype instanceof Object运行结果是ture,即People.prototype是Object的实例。
特性:通过构造函数方式新建一个对象时,新建的对象会从prototype属性上继承属性和方法。举个例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>trigger</title>
</head>
<body>

    <button class="btn">trigger</button>

    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>


        function People(name,age){
            this.name=name;
            this.age=age;
            console.log("我是: "+this.name+",我的年龄是:"+this.age)            
        }

        People.prototype.sayName=function(){
            console.log("hello,my name is:"+this.name)
        }
        People.prototype.hobby="code"

        var p1=new People("licai",24),
        p2=new People("zhangsan",20);

    </script>

</body>
</html>
Paste_Image.png

我们并没有在p1中定义sayName方法及hobby属性而是在People.prototype上定义了,但是却可以在p1上运行sayName()及hobby属性,其实是p1继承了People.prototype的sayName方法及hobby属性。

(四)、画出如下代码的原型图
function People (name){
  this.name = name;
  this.sayName = function(){
    console.log('my name is:' + this.name);
  }
}

People.prototype.walk = function(){
  console.log(this.name + ' is walking');  
}

var p1 = new People('饥人谷');
var p2 = new People('前端');
自画图.png
(五 )、以下代码中的变量age有什么区别
function People (){
  var age = 1 //  在函数里定义个一个局部变量age
  this.age = 10; //将10赋给相应对象的age,
}
People.age = 20; //给函数绑定一个值为20的age属性

People.prototype.age = 30;// 在函数的原型上绑定一个值为30的age属性
Paste_Image.png

二、代码

(一 )、创建一个 Car 对象,拥有属性name、color、status;拥有方法run,stop,getStatus ;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>
        function Car(name,color,status) {
            this.name=name;
            this.color=color;
            this.status=status;
        }

        Car.prototype.run=function () {
            this.status='running';
            console.log('The car is running!')
        };
        Car.prototype.stop=function () {
            this.status='stopping';
            console.log('The car is stopping!')
        };
        Car.prototype.getStatus=function () {
            console.log('The car is '+this.status+'!')
        };

        var car1=new Car('baoma','black','stopping')


    </script>

</body>
</html>
Paste_Image.png

在线预览地址:https://github.com/have-not-BUG/task/blob/master/renwu/renwu35/renwu35-1.html

(二 )、创建一个 GoTop 对象,当 new 一个 GotTop 对象则会在页面上创建一个回到顶部的元素,点击页面滚动到顶部。拥有以下属性和方法
ct属性,GoTop 对应的 DOM 元素的容器
target属性, GoTop 对应的 DOM 元素
bindEvent 方法, 用于绑定事件
createNode 方法, 用于在容器内创建节点

方法一、代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div.goToTop{
            position: fixed;
            top: 560px;
            left: 1200px;
            border: 1px solid red;
            border-radius: 3px;
            padding: 10px 20px;
            cursor: pointer;
            display: none;
        }
    </style>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>

</head>
<body>
<div class="ct">
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
</div>

    <script>

//        function goTop(ct) {
//            this.ct=ct;
//            this.target=$('<div class="goToTop">回到顶部</div>');
//            var goTopCt=this.ct,
//                goTopTr=this.target;
//
//            function canShow() {
//                var windowH=$(window).height(),
//                        scrollH=$(window).scrollTop();
//                if (scrollH>windowH){
//                    return true;
//                }
//                else {return false}
//            }
//            this.createNode=(function (){
//                $(goTopCt).append(goTopTr)
//            }());
//            this.bindEvent=(function () {
//                $(window).on("scroll",function () {
//                    if (canShow()){
//                        goTopTr.show()
//                    }
//                    else {goTopTr.hide()}
//                }) ;
//                goTopTr.on('click',function () {
//                    $(window).scrollTop(0)
//                });
//            }());
//        }
        function goTop(ct) {
            this.ct=ct;
            this.target=$('<div class="goToTop">回到顶部</div>');
            var goTopCt=this.ct,
                    goTopTr=this.target;

            function canShow() {
                var windowH=$(window).height(),
                        scrollH=$(window).scrollTop();
                if (scrollH>windowH){
                    return true;
                }
                else {return false}
            }

            this.createNode=function (){
                $(goTopCt).append(goTopTr)
            };
            this.createNode();

            this.bindEvent=function () {
                $(window).on("scroll",function () {
                    if (canShow()){
                        goTopTr.show()
                    }
                    else {goTopTr.hide()}
                }) ;
                goTopTr.on('click',function () {
                    $(window).scrollTop(0)
  // 或者使用动画效果慢慢往上升$('html,body').animate({"scrollTop":"0px"},800)
                });
            };
            this.bindEvent();
        }
        var GoTop1= new goTop('.ct');
    </script>

</body>
</html>

在线预览地址 https://github.com/have-not-BUG/task/blob/master/renwu/renwu35/renwu35-2A.html

方法二、

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div.goToTop{
            position: fixed;
            top: 560px;
            left: 1200px;
            border: 1px solid red;
            border-radius: 3px;
            padding: 10px 20px;
            cursor: pointer;
            display: none;
        }
    </style>
    <script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.js"></script>

</head>
<body>
<div class="ct">
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
    <p>内容1</p>
    <p>内容2</p>
    <p>内容3</p>
</div>

<script>

    function goTop(ct) {
        this.ct=ct;
        this.target=$('<div class="goToTop">回到顶部</div>');
        goTopCt=this.ct;
        goTopTr=this.target;
        this.createNode();
        this.bindEvent();
    }
    goTop.prototype={
            bindEvent:function () {
            $(window).on("scroll",function () {
                function canShow() {
                    var windowH=$(window).height(),
                            scrollH=$(window).scrollTop();
                    if (scrollH>windowH){
                        return true;
                    }
                    else {return false}
                }
                if (canShow()){
                    goTopTr.show()
                }
                else {goTopTr.hide()}
            }) ;
            goTopTr.on('click',function () {
                $('html,body').animate({"scrollTop":"0px"},800)
            });
        },
        createNode:function (){
            $(goTopCt).append(goTopTr)
        }
    };
    var GoTop1= new goTop('.ct');
</script>

</body>
</html>

在线预览地址:
https://github.com/have-not-BUG/task/blob/master/renwu/renwu35/renwu35-2B.html

(三 )、使用构造函数创建对象的方式完成轮播功能( 查看demo ),使用如下调用方式
function Carousel($node){
//todo...
}
Carousel.prototype = {
//todo ..
};

var $node1 = $('.ct').eq(0);
var $node2 = $('.ct').eq(1);
var carousel1 = new Carousel($node1);
var carousel2 = new Carousel($node2);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <style>
        ul,li,body,html{
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .img-ct>li{
            float: left;
            width: 310px;

        }
        .img-ct{
            position: absolute;
        }
        .clearfix:after{
            content: "";
            display: block;
            clear: both;
        }
        .lunbo{
            position: relative;
            width: 310px;
            height: 206px;
            overflow: hidden;
        }
        a{
            text-decoration: none;
            color: #fff;
        }
        .arrow{
            width: 20px;
            padding: 10px;
            background-color: #4E443C;
            border-radius: 20px;
            text-align: center;
            font-weight: bolder;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
        }
        .pre{
            left: 10px;
        }
        .next{
            right: 10px;
        }

    </style>
</head>
<body>
    <div id="c1" class="lunbo">
        <ul class="img-ct clearfix">
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/e1a09725c15c26a4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/d72dc312ec48d4f2.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/8726cd5c94bf76c9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/4f0449e2077d3895.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        </ul>
        <a class="pre arrow" href="#"><</a>
        <a class="next arrow" href="#">></a>
    </div>
    <div id="c2" class="lunbo">
        <ul class="img-ct">
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/e1a09725c15c26a4.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/d72dc312ec48d4f2.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/8726cd5c94bf76c9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li><a href="#">![](https://img.haomeiwen.com/i2166980/4f0449e2077d3895.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        </ul>
        <a class="pre arrow" href="#"><</a>
        <a class="next arrow" href="#">></a>
    </div>

    <script>

        function Carousel($node){
            this.$node=$node;
            var $ct=this.$ct=$node.find(".img-ct");
            var $liImg=$ct.children();
            this.imgNum=$liImg.length;
            this.imgWidth=$ct.children("li").width();
            $ct.width(this.imgWidth*this.imgNum);
            this.$next=$node.find(".next");
            this.$pre=$node.find(".pre");
            this.showMe();
        }
        Carousel.prototype={
            showMe: function () {
                var _this=this;
                console.log(this);
                this.$pre.on('click',function (e) {
                    e.preventDefault();
                    _this.playPre();
                });

                this.$next.on('click',function (e) {
                    e.preventDefault();
                    _this.playNext();
                });
            },
            playNext: function (){
                var $ct=this.$ct;
                $ct.animate({"left":0-this.imgWidth},600,function () {
                    $ct.append($ct.children().first());
                    $ct.css("left",0);
                });

            },
            playPre: function () {
                var $ct=this.$ct;
                $ct.prepend($ct.children().last());
                $ct.css("left",0-this.imgWidth);
                $ct.animate({"left":0},600);
            }

        };

// 新建对象注意应该写在后面,不能提前写!
    var c1 = new Carousel($('#c1'));
    var c2 = new Carousel($('#c2'));

// 或者使用遍历的方法
//        $(".lunbo").each(function () {
//            new Carousel($(this))
//
//        })

    </script>



    <!--<script>-->
        <!--var $liImg=$('.img-ct').children(),-->
                <!--imgNum=$liImg.length;-->
        <!--$('.img-ct').append($liImg.first().clone());-->
        <!--$('.img-ct').prepend($liImg.last().clone());-->
        <!--var trueImgNum=$('.img-ct').children().size(),-->
                <!--imgWidth=$('.img-ct li').width();-->
        <!--$('.img-ct').width(imgWidth*trueImgNum);-->
        <!--$('.img-ct').css({"left":0-imgWidth});-->
        <!--var i=1,-->
                <!--clock=false;-->

        <!--$(".next").on('click',function () {-->
            <!--if (clock){return}-->
            <!--clock=true;-->
            <!--playNext();-->
            <!--setTimeout(function () {-->
                <!--clock=false;-->
            <!--},600)-->
        <!--});-->

        <!--function playNext() {-->
            <!--if (i===imgNum+1){-->
                <!--$('.img-ct').css("left",0-imgWidth);-->
                <!--i=1;-->
            <!--}-->
            <!--$('.img-ct').animate({"left":0-imgWidth*(i+1)},600);-->
            <!--i=i+1;-->
            <!--console.log("我是playNext"+i);-->
        <!--}-->
        <!--function playPre() {-->
            <!--i = i - 1;-->
            <!--if (i === -1) {-->
                <!--$('.img-ct').css("left", 0 - imgWidth * imgNum);-->
                <!--i = imgNum - 1;-->
            <!--}-->
            <!--$('.img-ct').animate({"left":0-imgWidth*i},600);-->
            <!--console.log("我是playPre"+i);-->
        <!--}-->

        <!--$(".pre").on('click',function () {-->
            <!--if (clock){return}-->
            <!--clock=true;-->
            <!--playPre();-->
            <!--setTimeout(function () {-->
                <!--clock=false;-->
            <!--},600)-->
        <!--});-->

    <!--</script>-->

</body>
</html>

在线预览地址:https://github.com/have-not-BUG/task/blob/master/renwu/renwu35/renwu35-3.html

(四 )、使用构造函数创建对象的方式实现 Tab 切换功能
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        ul,li{
            display: inline-block;
            vertical-align: middle;
            font-size: 0;

        }
        li{
            list-style: none;
            border: 1px solid #1a1a1a;
            font-size: 20px;
            padding: 10px 10px;
            width: 200px;
            text-align: center;
            cursor: pointer;
        }
        .down{
            border: 1px solid #1a1a1a;
            width: 600px;
            height: 200px;
        }
        .content{
            display: none;
        }
        .down>.active{
            display: block;
        }
        .ctTab>.active{
            background-color: #ccc;
        }

    </style>
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
</head>

<body>
    <div id="wrap1">
        <ul class="ctTab">
            <li class="tab active">tab1</li>
            <li class="tab">tab2</li>
            <li class="tab">tab3</li>
        </ul>
        <div class="down">
            <div class="content active">内容1</div>
            <div class="content">内容2</div>
            <div class="content">内容3</div>
        </div>
    </div>
    <div id="wrap2">
        <ul class="ctTab">
            <li class="tab active">tab1</li>
            <li class="tab">tab2</li>
            <li class="tab">tab3</li>
        </ul>
        <div class="down">
            <div class="content active">内容1</div>
            <div class="content">内容2</div>
            <div class="content">内容3</div>
        </div>
    </div>

    <script>
        // 总体思路:点击处 获取index  邻居删除active 自己加上active

        //      详细思路
        //            $(".ctTab li").on("click",function () {
        //                var $this=$(this);
        //                var i=$(".ctTab li").index($this);
        //                $(".ctTab").children().eq(i).siblings().removeClass("active");
        //                $(".ctTab").children().eq(i).addClass("active");
        //                $(".down").children().eq(i).siblings().removeClass("active");
        //                $(".down").children().eq(i).addClass("active");
        //        })

        function changTab($node) {
            this.$node=$($node);
            this.$navLi=$($node).find(".ctTab li");
            this.$ctTab=$($node).find(".ctTab");
            this.$down=$($node).find(".down");
            this.bind();
        }
        // 下面这样也可以
        //        function changTab($node) {
        //            this.$node=$($node);
        //            this.$navLi=this.$node.find(".ctTab li");
        //            this.$ctTab=this.$node.find(".ctTab");
        //            this.$down=this.$node.find(".down");
        //            this.bind();
        //        }

        changTab.prototype={
            bind:function () {
                var _this=this;
                this.$navLi.on("click",function () {
                    var $this=$(this);
                    var i=_this.$navLi.index($this);
                    _this.$ctTab.children().eq(i).siblings().removeClass("active");
                    _this.$ctTab.children().eq(i).addClass("active");
                    _this.$down.children().eq(i).siblings().removeClass("active");
                    _this.$down.children().eq(i).addClass("active");
                })
            }

        };
        var changtab1=new changTab("#wrap1");
        var changtab2=new changTab("#wrap2");


    </script>
</body>
</html>

在线预览地址:https://github.com/have-not-BUG/task/blob/master/renwu/renwu35/renwu35-4.html

**本文版权归本人即简书笔名:该账户已被查封 所有,如需转载请注明出处。谢谢! *

上一篇下一篇

猜你喜欢

热点阅读