美文网首页
对象_原型

对象_原型

作者: 高进哥哥 | 来源:发表于2017-04-18 19:28 被阅读0次

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

    OOP:Object-oriented programming,面向对象程序设计,其中两个最重要的概念就是类和对象。类只是具备了某些属性和方法的抽象模型,而实际运用中需要一个一个实体,也就是需要对类进行实例化,类在实例化后就是对象。
    特性:

    • 继承性:子类自动继承父类中的属性和方法,并可以添加新的属性和方法。
    • 多态性:子类可以对父类中部分方法进行重写。
    • 封装性:将一个类的使用和实现分开,只保留部分接口和方法与外部联系

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

       function Person(name,age){
        this.name=name;
        this.age=age;
      }
      Person.prototype.showAge=function(){
          console.log("姓名:"+this.name+" 年龄:"+this.age);
      }
      var person=new Person("高进",24);
      person.showAge();
    

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

    JavaScript的每个对象都继承另一个对象,后者称为“原型”(prototype)对象。只有null除外,它没有自己的原型对象。原型对象上的所有属性和方法,都能被派生对象共享。这就是JavaScript继承机制的基本设计。通过构造函数生成实例对象时,会自动为实例对象分配原型对象。每一个构造函数都有一个prototype属性,这个属性就是实例对象的原型对象。
    每个函数都自动添加一个名称为prototype的属性,这是一个对象。
    每个对象都有一个内部属性proto(规范中没有指定这个名称,但是浏览器都这么实现的) 指向其构造函数的prototype属性,类的实例也是对象,其proto属性指向“类”的prototype。

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

    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(name+"run");
      };
      Car.prototype.stop=function(){
        console.log(name+"stop");
      };
      Car.prototype.getStatus=function(){
        console.log(this.name+this.status);
      }
      var car=new Car("法拉利","黄色","run");
      car.getStatus();
    

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

    1. ct属性,GoTop 对应的 DOM 元素的容器
    2. target属性, GoTop 对应的 DOM 元素
    3. bindEvent 方法, 用于绑定事件
    4. createNode 方法, 用于在容器内创建节点
       function GoTop(ct, target) {
          this.ct = ct;
          this.target = target;
          this.createNode();
          this.bindEvent();
        }
        GoTop.prototype.bindEvent = function () {
          $("." + this.target).on("click", function () {
            $(window).scrollTop(0);
          })
        }
        GoTop.prototype.createNode = function () {
          var node = "";
          node += '<button class="' + this.target + '" >回到顶部</button>'
          console.log(node);
          this.ct.append($(node));
        }
        var goTop = new GoTop($(".box"), "btn");
    

    相关文章

      网友评论

          本文标题:对象_原型

          本文链接:https://www.haomeiwen.com/subject/ygotzttx.html