Javascript 第五章总结:A trip to Objectville

前言

在以前的代码中,我们使用 primitive 类型的变量和 procedural manner 来执行脚本。但是,更好的办法是 object-oriented (面向对象)的。作者说:它能让我们 better in a programming sense,并且你不再想用原来的 procedural manner 的那种方法了。

什么是 Object,什么是 OO(Objective Oriented)?

Object的定义

JavaScript 中的 object 指的是: a collection of properties,这些 properties 中又包括它们的 name 和 value.

OO的定义

OO 指的是一种编程的思想,它包括两个要素:state s和 behaviors。通过对象的特征的引用来达到目的,而不是 procedual 那样一步一步来。
引用:

Objects that have state (like a car might have an oil and fuel level), and behavior (like a car can be started, driven and stopped).

In objec-oriented programming, we think in terms of objects rather than procedures.

对于 OO 的好处,作者这样表述:

object-oriented programming allows you to free your mind to think at a higher level.

Javascript 中的 object [state部分]

定义一个 object

格式:

  1. 开头有 var declaration 和 object 的名字
  2. 接下来各种 property 包含在 { } 中
  3. 每个 property 包含name:value,的格式
  4. 在 } 别忘了加 ;

范例:

基本操作

  1. 通过 dot notation 来 access a property,或者通过["nameOfProperty"]来达到目的,范例如:chevy.color 和 chevy['color']
  2. 改变 property 可以采用赋值的方式
  3. 增加一个新 property 可以采用赋值的方式
  4. 可以用 delete operator删除一个 property,格式:delete fido.dogYears.
    ###object 的实质
    object 的 var 类型实际上表表明了这是类似于 pointer 的储存着 reference 的值。
    因此,在函数进行传递的时候,由于传递的是地址, 所以在函数中处理的是 same object,因此在函数中的命令会改变它的值。

Javascript 中的 object [behavoir部分]

在 object 中添加函数

格式:先写一个 name,然后再写函数部分:function(parameter){}
范例:

state 和 behavior 之间的关系

Have you also notice these two interact? Like, we can't start a car if it doesn't have fuel, and the amount of fuel should get reduced as we drive the car. Kinda like read life, right?

使用关键字:this

在 object 中,value 和 behavoir 是相互影响的,因此当我们需要在 object 中的 behavior 调用 object 中的 value。
调用的方法是使用 this 这个 keyword. 表示 这个函数所在的 object 中的这个值,因此它是相对的。
格式:this.nameOfproperty

使用 for-in 用来iterate throngh an object's properties

格式:for (var .. in nameOfObject){
block;}
范例:for (var prop in chevy) {
console.log(...)
}





猜你喜欢

转载自www.cnblogs.com/FBsharl/p/10217282.html