对象_原型

2017-11-21  本文已影响0人  ShawnRong

问题1: OOP 指什么?有哪些特性

OOP指的是面向对象编程。就是将事物抽象成对象。
面向对象的三个基本特征是:封装、继承、多态。

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

function Car(brand){
    this.brand = brand;
    this.start = function(){
        console.log('gogogo');
    }
}

问题3: prototype 是什么?有什么特性

js本身不提供一个class的实现,js对象都有一个私有属性(称之为 [[Prototype]]),它持有一个连接到另一个称为其 prototype 对象(原型对象)的链接。该 prototype 对象又具有一个自己的原型,层层向上直到一个对象的原型为 null。JavaScript 中几乎所有的对象都是位于原型链顶端的Object的实例。

问题4:画出如下代码的原型图

prototype

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


function Car(name, color, status) {
  this.name = name;
  this.color = color;
  this.status = status;
}

Car.prototype.run = function() {
  console.log('run run run');
}

Car.prototype.stop = function() {
  console.log('stop');
}

Car.prototype.getStatus = function() {
  return this.status;
}

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

        function goTop($ct, $target){
          this.$ct = $ct;
          this.$target = $target;
          this.createNode();
          this.bindEvent();
        }

        goTop.prototype = {
          bindEvent: function(){
            this.$target.on('click', function(e){
              e.preventDefault();
              $('html,body').animate({
                scrollTop: 0
              }, 700);
            })
          },
          createNode: function(){
            this.$ct.append(this.$target);
          }
        }

        new goTop($('body'), $('<a href="#">top</a>'));
上一篇 下一篇

猜你喜欢

热点阅读