javaScript的面向对象简述

OOP 指什么?有哪些特性

面向对象程序设计(Object Oriented Programming):
是种具有对象概念的程序编程典范,同时也是一种程序开发的抽象方针。它可能包含数据、属性、代码与方法。对象则指的是类的实例。它将对象作为
程序的基本单元,将程序和数据封装其中,以提高软件的重用性、灵活性和扩展性,对象里的程序可以访问及经常修改对象相关连的数据。在面向对象程序编程里,计算机程序会被设计成彼此相关的对象。
面向对象有三大特性:封装,继承,多态


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

function Person(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.sayName = function(){
        console.log(this.name);
    }
}

var person1 = new Person('jirengu',23,'male');
var person2 = new Person('jrg',21,'female');

prototype 是什么?有什么特性

我们创建的每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法,如果按照字面意思来理解,那么prototype就是通过调用构造函数而创建的那个对象实例的原型对象。使用原型对象的好处是可以让所有对象实例共享它所包含的属性和方法。换句话说,我们不必在构造函数中定义对象实例的信息,而是可以将这些信息直接添加到原型对象中。

function Person(){
    this.prototype.name = 'jirengu';
    this.prototype.age = 23;
    this.prototype.sex = male;
    this.prototype.sayName = function(){
        console.log(this.name);
    }
}

var person1 = new Person();
person1.sayName()   //   jirengu

画出如下代码的原型图

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

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

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

    AutoMobile.prototype.run = function(){
        this.status = "run";
        console.log("It's running");
    };
    AutoMobile.prototype.stop = function(){
        this.status = "stop";
        console.log("It's stoped");
    };
    AutoMobile.prototype.getStatus = function(){
        console.log(this.status);
    };
    
    
}


var Car  = new AutoMobile('Cadillac','black','stop');

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


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

你可能感兴趣的:(javaScript的面向对象简述)