理解对象

JS 中的对象

JS 中的对象是一系列无序 key: value 的集合

比如

var obj = { a: 1, b: 2}
var person = {
    name: 'hunger',
    sayName: function(){
        console.log('My name is hunger')
    }
}

我们可以通过 对象.属性来获取对应属性的值

console.log(person.name)
person.sayName()

但假设我们定义一个函数

function sum(a, b){
    return a + b
}

console.log(sum.name)   // => sum
console.log(sum.length)  //2

会发现,函数 sum也有很多属性,从这个角度看,函数也是 js 对象的一种

OOP(Object-oriented programming, 面向对象编程)

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of "this" or "self"). In OOP, computer programs are designed by making them out of objects that interact with one another. There is significant diversity of OOP languages, but the most popular ones are class-based, meaning that objects are instances of classes, which typically also determine their type. -- 来自 wiki

面向对象的思路在我们生活中实际上很普遍。以开车为例,开车时司机拧钥匙、挂挡、踩油门,车开始启动

面向过程的写法

拧钥匙()
联通电路()
火花塞点火()
活塞运动()
内燃机启动()
司机挂挡()
变速箱工作()
踩油门()
活塞运动加快()
刹车解除()
连杆传输动力到轮子()
轮子运转()

面向对象的思路:一次性实现所有的流程

面向对象的写法

Car.拧钥匙()
Car.挂挡()
Car.踩油门()

面向对象的思路:把某个功能看成一个整体(对象),通过调用对象的某个方法来启动功能。在用的时候不去考虑这个对象内部的实现细节,在去实现这个对象细节的时候不用管谁在调用

面向对象的写法不仅更简洁,而且更可控。假设有两个车要启动,用面向过程的写法代码无法维护,而面向对象只需要

Car1.拧钥匙()
Car1.挂挡()
Car1.踩油门() 
Car2.拧钥匙()
Car2.挂挡()
Car2.踩油门()

参考

results matching ""

    No results matching ""