by Kris Baillargeon

通过克里斯·拜伦

学习使用JavaScript进行面向对象编程的基础知识(并增强您的编码能力!) (Learn the basics of object-oriented programming with JavaScript (and supercharge your coding abilities!))

As a moderator of the freeCodeCamp chat rooms, I spend a lot of time with new developers. Boy, are they eager to learn. For a lot us, this can be quite a challenging quality.

作为freeCodeCamp聊天室的主持人,我花了很多时间在新开发人员身上 。 男孩,他们渴望学习吗? 对于我们很多人来说,这可能是一个具有挑战性的品质。

In the case of object-oriented programming (OOP), this rings especially true. What the heck is a method and why is it so special? What’s the difference between a method and a property? Why do we even use object-oriented programming, and why is it essential to me as a developer? These are some questions I asked myself while learning OOP, and because you’re here, it’s safe to assume that you have, too.

在面向对象编程(OOP)的情况下,尤其如此。 什么是方法,为什么它如此特别? 方法和属性有什么区别 为什么我们甚至使用面向对象的程序,为什么对于我作为开发人员来说这是必不可少的? 这些是我在学习OOP时问自己的一些问题,并且因为您在这里,所以可以肯定地假设您也有。

在JavaScript中使用面向对象的编程 (Using Object-Oriented Programming with JavaScript)

Almost everything in JavaScript is an object. Somewhere behind the scenes, every piece of code you write is either written or stored with OOP. That’s one of the reasons why it’s so important to understand it. If you don’t then you’ll most likely never be able to read other developers’ code. On top of that, your code will never reach its full potential!

JavaScript中的几乎所有东西都是对象。 在幕后的某个地方,您编写的每段代码都是用OOP编写或存储的。 这就是理解它如此重要的原因之一。 如果您不这样做,那么您极有可能永远无法阅读其他开发人员的代码。 最重要的是,您的代码将永远无法发挥其全部潜能!

A new object is made in JavaScript by assigning a variable to two curly brackets, like this:

通过将变量分配给两个大括号来在JavaScript中创建一个新对象,如下所示:

var myObject = {};
// var myObject = new Object();  // Non recommended version, but it works

It’s that simple! You now have an object that can store any type of data you would store in a variable. There are many ways of inserting data into an object, but we’ll stick to the easiest methods right now.

就这么简单! 现在,您有了一个可以存储将存储在变量中的任何类型的数据的对象。 有多种方法可以将数据插入对象,但现在我们将坚持最简单的方法。

快速语法课 (Quick Syntax Lesson)

To end a line in JavaScript, when making a variable like this:

在制作这样的变量时,要在JavaScript中结束一行:

var a = 5;

var a = 5;

the “line” ends at the semicolon. When you’re making an object, the “line” will end with a comma, like so:

“行”以分号结尾。 制作对象时,“行”将以逗号结尾,如下所示:

myObject = { myProp: 5,  myOtherProp: 10,}
  • Property/Key: The name of an object variable. An example would be myProp in the above code. || Left hand side of assignments

    属性/键:对象变量的名称。 一个例子是myProp 在上面的代码中。 || 作业的左侧

  • Method : A function inside of an object, only available to that object. This is a type of property.方法:对象内部的函数,仅对该对象可用。 这是一种属性。
  • Value: The value of an object variable. An example would be 10, which is the value of myOtherProp. This can be any valid JavaScript datatype.

    值:对象变量的值。 一个例子是10,这是myOtherProp.的值myOtherProp. 这可以是任何有效JavaScript数据类型。

Only the last property in an object may not use a comma.

只有在一个对象中的最后一个属性可以不使用逗号。

Note: You may enclose your properties in single or double quotes. If there is a space in the property name, you must always use quotes. When using JSON, using quotes is not optional.

注意:您可以将属性用单引号或双引号引起来。 如果属性名称中有空格,则必须始终使用引号。 使用JSON时 ,使用引号不是可选的。

引用对象属性 (Referencing Object Properties)

点表示法 (Dot notation)

There are two ways of referencing an object, both having a name as reference. The most commonly used, dot notation, is what is primarily used. It looks like this:

有两种引用对象的方法,两种方法都有一个名称作为引用。 最常用的是点符号它是主要使用的符号。 看起来像这样:

var myObject = {
otherObject: {            one: 1,        two: 2      },
addFunction: function(x,y){ return x+y }
}
var dot = myObject.otherObject;console.log(dot);//evaluates to otherObject: {..props:vals..}

The above code goes into myObject and adds another object to it, otherObject via dot notation. Any name that can be used as a variable is suitable for use in dot notation. Dot notation is best practice for referencing any property that doesn’t include spaces.

上面的代码进入myObject 并向其中添加另一个对象otherObject 通过点表示法。 可以用作变量的任何名称都适用于点表示法。 点表示法是引用任何不包含空格的属性的最佳实践。

括号符号 (Bracket Notation)

var myObject = {  "Other Obj": {          one: 1,      two: 2    }}
var bracket = myObject["Other Obj"];
bracket.newProperty = "This is a new property in myObject";
console.log(bracket.newProperty);
//evaluates to myObject["Other Obj"].newProperty

The other way to reference objects is via bracket notation. This is only recommended if the object’s property contains a space, such as the property myObject[“Other Object”]; . In this case, using bracket notation is a must. When naming methods, don’t use spaces — otherwise the function can’t be called. Additionally, you can use quotes to name any property.

引用对象的另一种方法是通过括号符号。 仅当对象的属性包含空格时才建议这样做,例如,属性myObject[“Other Object”]; 。 在这种情况下,必须使用括号符号。 在命名方法时,请勿使用空格-否则无法调用该函数。 此外,您可以使用引号命名任何属性。

使用JavaScript IRL (Using JavaScript IRL)

Constructor Functions are worth mentioning, as we will be making our own form of constructor functions later on in this article. To do this, we must first learn two JavaScript keywords — newand this. You use the new keyword when referring to the constructor function.

建设者 函数值得一提,因为我们将在本文的后面部分构造自己的构造函数。 要做到这一点,首先要学会两个JavaScript关键字- 还有这个 。 引用构造函数时,请使用new关键字。

For the this keyword, it’s basically a fancy keyword for the last called function parent object. If it has no parent object, window will be its parent object. You can bind a function to this keyword using Function.bind(). Learn more here. But that’s a bit more advanced. Make any sense? Let’s look at some code:

对于this关键字,它基本上是最后一个调用函数的父对象的特殊关键字。 如果没有父对象,则window将为其父对象。 您可以将功能绑定到此 使用Function.bind ()的关键字 在这里了解更多 但这有点高级。 有道理吗? 让我们看一些代码:

var ConstructorForPerson = function(first, last, email) {  this.firstName = first;this.lastName = last;this.fullName = first + " " + last;this.eMail =  email;
}
var Bob = new ConstructorForPerson("bob", "brown", "bob122099@gmail.com");
console.log(Bob.eMail);
//evals "bob122099@gmail.com"

The above code will return a new object, Bob. That is the result of the constructor function, which will have the properties Bob.firstName, Bob.lastName, Bob.fullName, and Bob.eMail.

上面的代码将返回一个新对象Bob. 那是构造函数的结果,它将具有属性Bob.firstNameBob.lastNameBob.fullNameBob.eMail

Note that inside of a constructor function, instead of ending a line with a comma, it ends with a semicolon like you would expect inside a function. Optionally, to keep things simple, you can make your own constructor functions without using new or this. That’s what we’ll be doing today so we can see all the moving pieces better.

请注意,在构造函数内部,与其以逗号结尾,不如在函数内部以分号结尾。 (可选)为使事情简单,您可以使用自己的构造函数而无需使用new 或者这个 这就是我们今天要做的,因此我们可以更好地看到所有运动部件。

简单来说 (In Simple Terms)

Object-oriented programming is a way of structuring your code for optimal readability, use, and maintenance. With this in mind, let’s try coding a representation of Google as a business, including some functions of a normal company.

面向对象的编程是一种结构化代码以实现最佳可读性,使用和维护的方式。 考虑到这一点,让我们尝试编码Google的业务代表形式,包括普通公司的某些功能。

  • The Object — The Building/Management. This will contain all the information about any kind of employee, anything that can be done to an employee, including making a new one.

    对象-建筑物/管理 这将包含有关任何类型雇员的所有信息,可以对雇员进行的所有操作,包括创建新雇员。

  • The Properties — The Employees. This can be a manager or a desk clerk. This can be a list of employees. This can be your gross profit for this year. Pretty much anything.

    属性-员工 这可以是经理或办公桌文员。 这可以是员工列表。 这可以是您今年的毛利。 几乎任何东西。

  • The Methods — What Can Google Do? What Can The Employees Do? This is how new employees are made, as well as how they will “perform tasks”.

    方法-Google可以做什么? 员工可以做什么? 这就是新员工的培养方式以及他们“执行任务”的方式。

让我们编码! (Let’s Code!)

First, let’s look at our end result:

首先,让我们看一下最终结果:

var google = { //create {google}
employees: {           management: {            },
developers: {                 },
maintenance: {            }   },      NewEmployee: function(name, role, phone, idNumber) {  //create NewExployee()            var newEmployeeData = {        name: name,        role: role,        phone: phone,        idNumber: idNumber,        working: false,        hours: [],       }     //make new object to append to google.employees[role]        google.employees[role][name] = newEmployeeData;    //assign object to google.employees[role][name]
return  google.employees[role][name];  //return the new object directly from google.employees[role][name]        } //end NewEmployee  } //end {google}
google.NewEmployee("james", "maintenance", "2035555555", "1234521"); //create {google:employees:maintenance["james"]} from NewEmployee()
google.employees["maintenance"]["james"].clockInOut = function() { //create clockInOut() - default false         if(this.working) {         this.hours[this.hours.length - 1].push(Date.now());         this.working = false;         return this.name + " clocked out at " + Date.now();        }       else{         this.hours.push([Date.now()]);         this.working = true;         return this.name + " clocked in at " + Date.now();        }
return "Error"     //if above doesn't work, "Error" }
google.employees["maintenance"]["james"].clockInOut(); //clock James in or out, returns a string w/ the time & state

Daunting?

令人生畏的?

Let’s break it down into smaller pieces. To start, we’ll make a global object called Google. It will contain another object for employees, which will contain more objects for each role and its individual employees.

让我们将其分解为较小的部分。 首先,我们将创建一个名为Google的全局对象。 它将为员工包含另一个对象,该对象将为每个角色及其单个员工包含更多对象。

So what will this look like in code? For the sake of keeping things easy, we’re going to make a constructor using a normal function. It will have 7 properties: name, role, phone, idNumber, working, and hours.

那么这在代码中会是什么样? 为了使事情变得简单,我们将构造一个构造函数 使用正常功能。 它将具有7个属性: namerole, phoneidNumber working , 和hours

In addition, it will have 1 method: clockInOut(), which will look at the working property to update hours.

此外,它将有1个方法: clockInOut(),它将查看working属性以更新hours.

Let’s break it down.

让我们分解一下。

First, we’re going to update our Google object with the NewEmployee() constructor function. Remember, instead of using the regular JavaScript constructor function, we’ll be using our own.

首先,我们将使用NewEmployee()构造函数更新Google对象。 请记住,我们将使用自己JavaScript而不是常规JavaScript构造函数。

Note: Pay attention to syntax as it will switch around a bit depending on what you’re doing

注意:请注意语法,因为语法会根据您的操作而有所变化

Also note: These examples will not run properly as they do not have the correct dependencies/properties/variables. Most if not all functionality from the final product will return an error. If you run the final product, however, everything should work fine.

另请注意:这些示例将不正确运行,因为它们没有正确的依赖关系/属性/变量。 最终产品的大多数功能(如果不是全部功能)将返回错误。 但是,如果您运行最终产品,则一切都会正常运行。

var google = { //create {google}
employees: {           management: {
},           developers: {
},
maintenance: {
}         }, //<--this comma is unnecessary right now but when we add more object properties it will be necessary}

employees holds other objects which are various roles in the company: management, developers, and maintenance. We will be adding an employee via the employee’s role, in this case, maintenance.

employees还拥有公司中其他各种角色: managementdevelopersmaintenance 。 我们将通过员工角色(在这种情况下为维护)来添加员工。

var google = {  NewEmployee: function(name, role, phone, idNumber) {    var newEmployeeData = {      name: name,      role: role,      phone: phone,      idNumber: idNumber,      working: false,      hours: [],     }     //make new object to append to google.employees[role]        google.employees[role][name] = newEmployeeData;    //assign object to google.employees[role][name]
return  google.employees[role][name];  //return the new object directly from google.employees[role][name]  }}

Our “constructor” function”. Pretty straightforward, it takes a new object and appends it to the corresponding role.

我们的“构造函数”。 非常简单,它需要一个新对象并将其附加到相应的角色。

google.employees["maintenance"]["james"].clockInOut = function() { //create clockInOut() - default false         if(this.working) {         this.hours[this.hours.length - 1].push(Date.now());         this.working = false;         return this.name + " clocked out at " + Date.now();        }       else{         this.hours.push([Date.now()]);         this.working = true;         return this.name + " clocked in at " + Date.now();        }
return "Error" //if above doesn't work, "Error" }
google.employees["maintenance"]["james"].clockInOut(); //call clockInOut()

This is where it might get confusing. Remember that the keyword this is just a funny way to say the calling function’s parent object? In the above, we add the method clockInOut() to our code. We invoke it simply by calling it. If working is false, it will create a new array with a Unix timestamp at index 0. If you’re already working, it will just append a Unix timestamp to the last created array, creating an array that looks kind of like this: [1518491647421, 1518491668453] with the first timestamp being when the employee “clocks in”, the second being when the employee “clocks out”.

这可能会使您感到困惑。 请记住,关键字this 说调用函数的父对象只是一种有趣的方式? 在上面的代码中,我们将方法clockInOut ()添加到了代码中。 我们只需调用它即可调用它。 如果work为false,它将创建一个带有Unix时间戳索引为0的新数组。如果您已经在工作,它将Unix时间戳附加到最后创建的数组,从而创建一个看起来像这样的数组:[ 1518491647421、1518491668453],第一个时间戳是员工“进门”的时间,第二个时间戳是员工“进门”的时间。

Now we’ve seen how using OOP can be practical! Each individual employee can “clock in” and “clock out” with a simple function call, and all you have to know is their name and role!

现在我们已经看到了使用OOP的实用性! 每个员工都可以通过一个简单的函数调用“拨入”和“拨出”,您只需要知道他们的名字和角色!

This can, of course, be optimized to do something like look at an ID number instead of their role and name, but let’s not over-complicate things. Below we bring everything back into one program. Slightly less scary, right?

当然,可以对此进行优化,以执行类似于查看ID号的操作,而不是查看其角色和名称,但是我们不要使事情复杂化。 下面,我们将所有内容重新整合到一个程序中。 有点吓人吧?

var google = { //create {google}
employees: {           management: {      },      developers: {      },
maintenance: {      }         },      NewEmployee: function(name, role, phone, idNumber) { //create NewExployee()            var newEmployeeData = {        name: name,        role: role,        phone: phone,        idNumber: idNumber,        working: false,        hours: [],       }     //make new object to append to google.employees[role]        google.employees[role][name] = newEmployeeData;    //assign object to google.employees[role][name]
return  google.employees[role][name];  //return the new object directly from google.employees[role][name]        }//end NewEmployee  } //end {google}
google.NewEmployee("james", "maintenance", "2035555555", "1234521"); //create {google:employees:maintenance["james"]} from NewEmployee()
google.employees["maintenance"]["james"].clockInOut = function() { //create clockInOut() - default false         if(this.working) {         this.hours[this.hours.length - 1].push(Date.now());         this.working = false;         return this.name + " clocked out at " + Date.now();        }       else{         this.hours.push([Date.now()]);         this.working = true;         return this.name + " clocked in at " + Date.now();        }
return "Error" //if above doesn't work, "Error" }
google.employees["maintenance"]["james"].clockInOut(); //call clockInOut()

Using Object Oriented Programming can not only make your code more powerful, but also much more readable to other developers. Feel free to contact me through Github for projects, Free Code Camp info, Javascript/HTML/CSS help, to encourage me to write a tutorial on using JSON and APIS, or to talk about cats!

使用面向对象的编程不仅可以使您的代码更强大,而且对其他开发人员也更具可读性。 请随时通过Github与我联系以获取项目, 免费的代码营信息,Javascript / HTML / CSS帮助,鼓励我编写有关使用JSON和APIS的教程或谈论猫!

By the way, if you didn’t know, everything taught in this tutorial as well as ANYTHING you need to know about vanilla Javascript, HTML, CSS and more, you can count on MDN to have an extensive amount of knowledge on it. It’s basically Google for web developers! It’s also 1220% free and open source.

顺便说一句,如果您不知道本教程中教授的所有内容以及有关原始Javascript,HTML,CSS等的任何知识,则可以依靠MDN来获得大量的知识。 基本上是面向网络开发人员的Google! 它还是1220%的免费开放源代码。

Don’t forget to clap & follow if you enjoyed! More articles coming soon! :)

如果您喜欢的话,别忘了拍手跟着! 更多文章即将推出! :)

Keep up with me on Instagram @krux.io

跟我上Instagram @ krux.io

FURTHER LEARNING ON MDN:

关于MDN的进一步学习:

OOP FOR BEGINNERS

适合初学者

GLOBAL OBJECTS

全球对象

JSON TUTORIAL

JSON教程

USING JSON IN JAVASCRIPT — GLOBAL JSON OBJECT

在JAVASCRIPT中使用JSON —全局JSON对象

KEYWORD THIS

关键字this

CONSTRUCTOR FUNCTIONS

构造函数

翻译自: https://www.freecodecamp.org/news/intro-to-object-oriented-programming-oop-with-javascript-made-easy-a317b87d6943/

了解使用JavaScript进行面向对象编程的基础(并增强您的编码…相关推荐

  1. System Verilog面向对象编程(OPP)基础——类(class)的基本使用

    该文主要是笔者梳理绿皮书对应章节的内容 System Verilog面向对象编程OPP基础--类(class)的基本使用 面向对象编程 概述 考虑名词而非动词 编写第一个类class OOP术语 创建 ...

  2. java零基础Ⅰ-- 6.面向对象编程(基础部分)

    java零基础Ⅰ-- 面向对象编程(基础部分) 类与对象 类与对象引出 类与对象概述 快速入门 类与对象的区别和联系 对象在内存中存在形式 属性/成员变量/字段 注意事项和细节说明 如何创建对象 如何 ...

  3. java学习笔记-第七章:面向对象编程(基础部分)

    第七章:面向对象编程(基础部分) 总体内容 类与对象 引出类与对象 类与对象概述 类与对象的关系示意图 属性概念及其细节 类与对象快速入门案例 对象内存布局 类与对象内存分配机制 引申:java内存的 ...

  4. S.O.L.I.D 是面向对象设计(OOD)和面向对象编程(OOP)中的几个重要编码原则

    注:以下图片均来自<如何向妻子解释OOD>译文链接:http://www.cnblogs.com/niyw/archive/2011/01/25/1940603.html <How ...

  5. JavaScript 的面向对象编程

    发现一个介绍JavaScript面向对象编程的文章,大家可以下下看看:http://pan.baidu.com/share/link?shareid=69566&uk=2802880612 本 ...

  6. JavaScript(四)——面向对象编程、BOM、DOM、表单验证、jQuery

    文章目录 1. 面向对象编程 2. 操作BOM对象(重点) 3. 操作DOM对象(重点) 4. 操作表单(验证) 5. jQuery 1. 面向对象编程 (1) 原型对象 javascript.Jav ...

  7. javascript俄罗斯方块 面向对象编程(jQuery)(附带百度网盘链接)

    这个俄罗斯方块游戏是通过javascript面向对象编程的方法编写,代码结构分为游戏类(Game.js),方块类(block.js),地图类(Map.js),方块形状对象类(blockjson.js) ...

  8. 第06章_面向对象编程(基础)

    本章专题与脉络 学习面向对象内容的三条主线 Java类及类的成员:(重点)属性.方法.构造器:(熟悉)代码块.内部类 面向对象的特征:封装.继承.多态.(抽象) 其他关键字的使用:this.super ...

  9. 用Javascript实现面向对象编程(封装,抽象,继承,多态)

    OO的特点:封装.抽象.继承.多态. 封装:在 面向对象语言中,封装特性是由类来体现的,我们将现实生活中的一类实体定义成类,其中包括属性和行为(在Java中就是方法),就好像人类,可以具有 name, ...

最新文章

  1. Array 数组去重 总结10方法(7)
  2. spacemacs各种问题修复方法
  3. ubuntu 编译源码包 dsc diff.gz orig.tar.gz
  4. C#利用Graphics类绘制进阶--绘制商品69码EAN-13
  5. 二维“有序”数组查找问题
  6. php扩展xdebug安装
  7. 南瓜电影 7 天内全面 Serverless 化实践
  8. python中从键盘输入的代码_Python读取键盘输入的2种方法
  9. 【原创】2009个性签名和流行语搜集
  10. 垃圾回收算法简单介绍——JVM读书笔记lt;二gt;
  11. c语言队列原理的实现,c印记(十二):队列queue原理与实现
  12. spark 架构_深入研究Spark内部和架构
  13. jvm延迟偏向_用于偏向硬币翻转模拟的Python程序
  14. [LeetCode] 234. Palindrome Linked List 回文链表
  15. 集成测试用例_如何评估测试用例的有效性?
  16. centos6 yum源_Centos6安装Zabbix3.4.15注意事项
  17. MongoDB是我想要的存储么?
  18. 计算机核心期刊加拿大,ssci或cssci期刊北京大学图书馆版核心期刊国外学术.doc...
  19. pinterest类网站差异化发展 时光轴成稀饭网突围利器
  20. 冰冻三尺非一日之寒,坚持,坚持,再坚持!

热门文章

  1. 离开小厂进大厂的第一周,BTAJ大厂最新面试题汇集,面试总结
  2. linux mysql 运行状态_Linux中使用mysqladmin extended-status配合Linux命令查看MySQL运行状态...
  3. k8s的ingress使用
  4. react事件处理函数中绑定this的bind()函数
  5. soapui自带的webservice实例 MockService
  6. [Drupal] Submit and redirect back to the modify page
  7. node搭建服务器,写接口,调接口,跨域
  8. jmeter对oracle压力测试
  9. Leetcode之javascript解题(No33-34)
  10. crontab里shell脚本将top信息写入文件