对象,原型

2016-10-17  本文已影响0人  Iswine

OOP 指什么?有哪些特性?

OPP(Object Oriented Programming)意为面向对象的编程,那问题来了,什么是面对对象呢?
举个例子,齿轮是连接机械制动的工具,其目的是让机械合理的运转。在使用齿轮之前,必然的要制造一系列齿轮。如果我们看重每一个齿轮的大小、结构、参数,且每一个齿轮都形状各异,那么无疑会使工作量剧增。所以,实际生产过程中国家规定了一系列标准,使得齿轮的尺寸模态化,让工程师只注重齿轮安装的位置而非齿轮本身的结构特点。
类似的,在程序编写过程中,我们通常所说的“”造轮子“”就类似于上例中的标准制定。它使得程序具有复用性,能够明确的实现某一具体的功能,使得程序员更加注重工程项目的需求分析,而非某一具体功能实现的内在逻辑,极大地缩短项目周期。所以,面向对象的编程是一种哲学思想。
其特性有三点:

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

function Student(name,score){
    this.name = name;
    this.age = 8;
    this.score = score;
    this.say = function(){
        console.log(this.name + "这次考了" + this.score + "分。")
    }
}
var xiaoming = new Student("小明",85);
xiaoming;  //Student {name: "小明", age: 8, score: 85}
var xiaohua = new Student("小花",90);
xiaohua;  //Student {name: "小花", age: 8, score: 90}

prototype 是什么?有什么特性?

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

以下代码中的变量age有什么区别?

function People (){
  var age = 1   //People函数的局部变量,只在People这个作用域生效;
  this.age = 10;  //不仅是People的属性,由他创建的原型都将继承该属性以及它的值;
}
People.age = 20; //仅仅将People这个对象age属性的值改为20;

People.prototype.age = 30; //给People的原型对象赋予属性age=30;

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

function Car(){
    this.name = "BMW";
    this.color = "white";
    this.status = "static"
    this.run = function() {
        return this.status = "running";
    }
    this.stop = function() {
        return this.status = "static";
    }
    this.getStatus = function(){
        return this.status;
    }
}

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

        function GoTop($ct,$target){
            this.ct = $ct;
            this.target = $target;
        }
        GoTop.prototype.bindEvent = function () {
            this.target.on("click",function(){
                $(window).scrollTop(0);
            })
        };
        GoTop.prototype.createNode = function () {
            this.ct.append(this.target);
        };
        var webBody = new GoTop($("body"),$("<button class='btn'>回到顶部</button>"));
        webBody.createNode();
        webBody.bindEvent();
上一篇 下一篇

猜你喜欢

热点阅读