对象-原型

2017-07-04  本文已影响0人  madpluto

1. OOP 指什么?有哪些特性

Object-oriented programming的缩写,即面向对象程序设计,其中两个最重要的概念就是类和对象。类只是具备了某些功能和属性的抽象模型,而实际应用中需要一个一个实体,也就是需要对类进行实例化,实例化一个类后就可以生成一个对象。

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

function Person(name,age){
  this.name = name;
  this.age = age
  this.slogan = function() {
    console.log('My name is: ' + this.name);
  }
}
var p = new Person('liyang',18);
p.slogan(); // My name is : liyang

3. prototype 是什么?有什么特性

在Javascript中任何一个函数在声明的同时,会给这个函数添加一个prototype属性,同时生成一个对象,prototype属性就指向这个对象,此对象称为函数的原型对象,原型对象里有个constructor属性,constructor属性又指向这个函数本身;每当以这个函数为构造函数生成一个新的对象时,新的对象里proto属性也指向这个原型对象。

4. 画出如下代码的原型图

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('前端');
image.png

5. 创建一个 Car 对象,拥有属性name、color、status;拥有方法run,stop,getStatus

1. `ct`属性,GoTop 对应的 DOM 元素的容器
2.  `target`属性, GoTop 对应的 DOM 元素
3.  `bindEvent` 方法, 用于绑定事件
4 `createNode` 方法, 用于在容器内创建节点
function Car (name,color,status){
    this.name = name;
    this.color = color;
    this.status = status;
}
Car.prototype={
  run:function(){},
  stop:function(){},
  getStatus:function(){}
}

6. 创建一个 GoTop 对象,当 new 一个 GotTop 对象则会在页面上创建一个回到顶部的元素,点击页面滚动到顶部。拥有以下属性和方法

<!DOCTYPE html>
<html>

<head>
    <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
    <style>
    .ct {
        width: 1000px;
        height: 1000px;
        background: blue;
    }
    </style>
</head>

<body>
    <div class="ct"></div>
    <script>
    function GoTop(ct) {
        this.ct = ct;
        this.target = $('<button>GoTop</button>');
        this.bindEvent();
        this.createNode();
    }
    GoTop.prototype = {
        bindEvent: function() {
            var _this = this;
            this.target.on('click', function() {
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow');
            });
        },
        createNode: function() {
            this.target.css({
                position: "absolute",
                bottom: 20,
                right: 20
            });

            this.ct.css({
                position: "relative"
            }).
            append(this.target);
        }
    };
    new GoTop($('.ct'));
    </script>
</body>

</html>

7. 使用木桶布局实现一个图片墙

http://js.jirengu.com/xiheqegape/2/edit

上一篇 下一篇

猜你喜欢

热点阅读