javascript基础知识对象对象操作

You’ve probably heard the term ‘Object Oriented Programming’ or ‘OOP’ among developers or on the internet, this article serves as an introduction to the concept of objects and how we can use them in our code.

您可能已经在开发人员中或在互联网上听说过“面向对象编程”或“ OOP”一词,本文将介绍对象的概念以及如何在代码中使用它们。

什么是物体? (What is an object?)

Put simply, an object is a collection of data sorted into key/value pairs. To keep a running example in this article, let’s consider your kitchen to be an object. Inside your kitchen, you have a stove, an oven, a refrigerator, a sink, and some cupboards — and maybe some kitchens have a toaster oven, and others don’t. Each of these things are the keys in the key/value pairs I was talking about. The values would be whatever data represents those keys. Written in JavaScript, our kitchen object might look like this…

简而言之,对象是分类为键/值对的数据集合。 为了使本文中的示例保持运行状态,让我们将厨房视为一个对象。 在厨房内部,您有炉子,烤箱,冰箱,水槽和一些橱柜-也许有些厨房有电烤箱,而有些则没有。 这些都是我在谈论的键/值对中的键。 这些值可以是代表这些键的任何数据。 我们的厨房对象使用JavaScript编写,可能看起来像这样……

So we used curly braces to define an object, then separated key/value pairs with commas.

因此,我们使用花括号定义一个对象,然后用逗号分隔键/值对。

对象数据类型 (Object Datatypes)

You’re not limited to strings, integers, and booleans for your values. You can also use arrays, more objects, and heck, you could even use an array of objects.

您的值不限于字符串,整数和布尔值。 您还可以使用数组,更多对象,甚至可以使用对象数组。

Consider the fact that a stove has burners, and can use a variety of heating methods — it’s starting to sound like an object itself, and we can definitely put an object inside of an object, this is how it would look…

考虑一下这样一个事实:火炉带有燃烧器,可以使用多种加热方法-它听起来像是一个物体本身,我们可以肯定地将一个物体放在一个物体内部,这就是它的外观……

let kitchen = {
stove: {
brand: "Kenmore",
burners: 4,
heatingMethod: "induction",
},
oven: "Kenmore",
refrigerator: "Whirlpool",
sink: "Sterling",
cupboards: 6,
};

Whoa, object-ception. All we had to do was add more curly braces and start writing another object, right there inside our kitchen object. We call this ‘nesting objects’, think like Russian dolls — one object inside another. Let’s add some more information to the oven, like how many racks it has, what its heating method is, and what’s being stored in that drawer underneath…

哇,对象接受。 我们要做的就是添加更多的花括号,然后开始在我们的厨房对象内部编写另一个对象。 我们称其为“嵌套对象”,就像俄罗斯娃娃一样思考-一个对象在另一个对象内。 让我们向烤箱中添加更多信息,例如烤箱有多少个架子,加热方法是什么以及下面的抽屉中存储了什么……

let kitchen = {
stove: {
brand: "Kenmore",
burners: 4,
heatingMethod: "induction",
},
oven: {
brand: "Kenmore",
racks: 2,
heatingMethod: "electric",
drawer: ["glass baking dish", "baking tray", "muffin pan"],
},
refrigerator: "Whirlpool",
sink: "Sterling",
cupboards: 6,
};

We were able to add an array as a value by just adding the square brackets and putting comma-separated strings. I imagine you’re seeing a pattern by now, but let’s think about how a refrigerator might look. I’ve very pointedly not used the term ‘fridge’, because a refrigerator (usually) has a cooling compartment, and a freezing compartment — the fridge and the freezer. The fridge usually has some drawers at the bottom, and a few shelves. Let’s see what a refrigerator broken up into two objects would look like…

通过添加方括号并放入逗号分隔的字符串,我们能够将数组添加为值。 我想您现在正在看到一种模式,但是让我们考虑一下冰箱的外观。 我非常明确地没有使用“冰箱”一词,因为冰箱(通常)具有一个冷却室和一个冷冻室-冰箱和冷冻室。 冰箱通常在底部有一些抽屉,还有一些架子。 让我们看看将冰箱分解成两个对象的样子……

let kitchen = {
stove: {
brand: "Kenmore",
burners: 4,
heatingMethod: "induction",
},
oven: {
brand: "Kenmore",
racks: 2,
heatingMethod: "electric",
drawer: ["glass baking dish", "baking tray", "muffin pan"],
},
refrigerator: {
brand: "Whirlpool",
fridge: {
drawers: 2,
shelves: 3,
temp: 40,
},
freezer: {
shelves: 1,
temp: 0,
iceMaker: false,
},
},
sink: "Sterling",
cupboards: 6,
};

Whoa, that was a lot! We turned the refrigerator into an object with three keys — fridge, freezer, and brand — and made fridge and freezer into objects, too. Next up is the sink, this should be an easy one to update. A sink has a faucet (the controls for the water flow), a spout, and either one or two sinks. Some also come with a disposal unit in the drain…

哇,好多! 我们将冰箱变成具有三个键的对象(冰箱,冰柜和品牌),并将冰箱和冰柜也变成对象。 接下来是接收器,这应该很容易更新。 一个水槽有一个水龙头(水流控制装置),一个喷口和一个或两个水槽。 有些还带有排水装置……

let kitchen = {
stove: {
brand: "Kenmore",
burners: 4,
heatingMethod: "induction",
},
oven: {
brand: "Kenmore",
racks: 2,
heatingMethod: "electric",
drawer: ["glass baking dish", "baking tray", "muffin pan"],
},
refrigerator: {
brand: "Whirlpool",
fridge: {
drawers: 2,
shelves: 3,
temp: 40,
},
freezer: {
shelves: 1,
temp: 0,
iceMaker: false,
},
},
sink: {
brand: "Sterling",
faucetType: "mixer",
spoutType: "hose",
sinks: 1,
disposal: false,
},
cupboards: 6,
};

Nothing particularly new there, but stay with me, because I saved the best for last. For the cupboards, we’re going to use an array of objects. Here’s how it’ll look…

那里没有什么特别新鲜的东西,但请留在我身边,因为我将最好的留到了最后。 对于橱柜,我们将使用一系列对象。 这是它的外观……

let kitchen = {
stove: {
brand: "Kenmore",
burners: 4,
heatingMethod: "induction",
},
oven: {
brand: "Kenmore",
racks: 2,
heatingMethod: "electric",
drawer: ["glass baking dish", "baking tray", "muffin pan"],
},
refrigerator: {
brand: "Whirlpool",
fridge: {
drawers: 2,
shelves: 3,
temp: 40,
},
freezer: {
shelves: 1,
temp: 0,
iceMaker: false,
},
},
sink: {
brand: "Sterling",
faucetType: "mixer",
spoutType: "hose",
sinks: 1,
disposal: false,
},
cupboards: [
{ location: "below sink", contents: [] },
{ location: "above stove", contents: [] },
{ location: "left of stove", contents: [] },
{ location: "right of stove", contents: [] },
{ location: "below counter", contents: [] },
{ location: "above counter", contents: [] },
],
};

Phew, that’s a lot of code! But don’t let it overwhelm you, this is just taking basic principals of objects and adding them together in creative ways. You might have noticed that I left empty arrays in the ‘contents’ field for each of the cupboards. Partially, this was to keep the code shorter, but it also sets us up for some fun with methods later on.

ew,这是很多代码! 但是,不要让它不知所措,这只是采用对象的基本原理,并以创造性的方式将它们添加在一起。 您可能已经注意到,我在每个柜子的“内容”字段中保留了空数组。 在某种程度上,这是为了使代码更短,但同时也使我们为以后的方法带来一些乐趣。

So, now that we’ve built this object, you must be wondering..

因此,既然我们已经构建了这个对象,您一定会感到奇怪。

如何获取信息? (How do I access the information?)

Great question, the easiest way to access information in an object is through ‘dot notation’. The kitchen is the object, and you want to access the information regarding it. For the sake of simplicity, we’ll assume you just want to display this information in the console. Assuming your code contains the object we built above, you can type the following to see the entire object…

很大的问题,访问对象中信息的最简单方法是通过“点符号”。 厨房是对象,您想访问有关它的信息。 为了简单起见,我们假设您只想在控制台中显示此信息。 假设您的代码包含我们上面构建的对象,则可以键入以下内容以查看整个对象……

console.log(kitchen)

Not a shocker, huh? You just got everything you typed, but in the console. Let’s say you’re only interested in information about your refrigerator right now, you could return just the fridge by typing…

不会令人震惊吧? 您只需输入所有内容,即可在控制台中找到。 假设您现在仅对有关冰箱的信息感兴趣,可以通过键入以下内容仅退还冰箱...

console.log(kitchen.refrigerator)

We used a period to access a tier of information within that object. This is dot notation — using a dot to move through your object. The above code should console log the entire object for your kitchen. Let’s take it deeper and see what we can find out about the fridge…

我们使用了一段时间来访问该对象内的一层信息。 这是点符号-使用点在对象中移动。 上面的代码应控制台记录您厨房的整个对象。 让我们更深入地了解我们对冰箱的了解...

console.log(kitchen.refrigerator.fridge)

Now we just get the object containing the number of drawers, shelves, and the temperature. And if we only want to know how many drawers are in the fridge in our kitchen? You guessed it, we add another period…

现在,我们只得到包含抽屉数量,架子和温度的对象。 如果我们只想知道厨房冰箱里有多少个抽屉? 您猜对了,我们再加一个句号…

console.log(kitchen.refrigerator.fridge.drawers)

Now, if you used the object example above, you should just get the number 2 in your console. Pretty simple, right? Just to make sure, let’s see what happens when we try to see what’s in the drawer under the oven…

现在,如果您使用上面的对象示例,则应该在控制台中获得数字2。 很简单,对吧? 为了确保这一点,让我们看看尝试查看烤箱下方抽屉中的内容时发生了什么……

console.log(kitchen.oven.drawer)

We get an array of strings, and now that we’re getting an array, we can definitely access this like an array, using square brackets to determine which index of the array we want to see…

我们得到了一个字符串数组,现在我们得到了一个数组,我们绝对可以像访问数组一样访问它,使用方括号来确定我们要查看的数组索引。

console.log(kitchen.oven.drawer[1])

And now we can access the baking tray in the drawer. Pretty neat huh?

现在我们可以进入抽屉中的烤盘了。 相当整洁吧?

At this point you could start writing functions to push() to the kitchen.cupboards[2].contents, or to say that kitchen.sink.brand = "Whirlpool", and that would be absolutely fine, but there is a better way…

在这一点上,您可以开始编写将push()kitchen.cupboards[2].contents函数,或者说kitchen.sink.brand = "Whirlpool" ,那绝对没问题,但是有更好的方法…

对象方法 (Object Methods)

I left one item off the list at the start of this article when I was telling you what data types an object could take — an object can also contain functions, which we call methods. These methods stay specific to the object in which they are created, clearing up your global scope. Let’s add a simple method to add an item to the drawer under the oven. For the sake of brevity, I’ll leave a lot of the object out of this snippet…

在我告诉您对象可以采用的数据类型时,我在本文开头没有列出任何内容-对象还可以包含函数,我们称其为方法。 这些方法特定于创建它们的对象,从而清除了全局范围。 让我们添加一个简单的方法,将物品添加到烤箱下的抽屉中。 为了简洁起见,我将在此代码段中省略很多对象……

let kitchen = {
oven: {
brand: "Kenmore",
racks: 2,
heatingMethod: "electric",
drawer: ["glass baking dish", "baking tray", "muffin pan"],
},
addToDrawer: function (item) {
this.oven.drawer.push(item);
},
};

So you’ll notice the keyword ‘this’ in the function, ‘this’ is something that, when used in a method, refers to the object in which it is called. To get the same functionality from a function declared outside of that object, we’d need to address the object directly using the variable name ‘kitchen’.

因此,您会注意到函数中的关键字“ this”, “ this”在方法中使用时,是指在其中调用它的对象。 为了从该对象外部声明的函数中获得相同的功能,我们需要使用变量名称“ kitchen”直接寻址该对象。

In order to use this method we just created, you only need to access it through ‘kitchen’ and then call it like normal. Here’s an example you can try to prove that it works…

为了使用我们刚刚创建的这种方法,您只需要通过“厨房”访问它,然后像平常一样调用它即可。 这是一个示例,您可以尝试证明它有效……

console.log(kitchen.oven.drawer);
kitchen.addToDrawer("cake tin");
console.log(kitchen.oven.drawer);

Or in other words, look at the array, push to the array, then look at the array again.

或者换句话说,查看数组,推送到数组,然后再次查看数组。

You can make these methods as complex as you like, building on top of the basics I’ve demonstrated here. For example, you could build a method to add items to any given cupboard…

您可以在我在此演示的基础知识的基础上,使这些方法尽可能复杂。 例如,您可以构建一种将物品添加到任何给定橱柜中的方法…

let kitchen = {
cupboards: [
{ location: "below sink", contents: [] },
{ location: "above stove", contents: [] },
{ location: "left of stove", contents: [] },
{ location: "right of stove", contents: [] },
{ location: "below counter", contents: [] },
{ location: "above counter", contents: [] },
],
addToCupboard: (index, item) => {
this.cupboards[index].contents.push(item)
},
};

Taking into account the fact that arrays start at index 0, we could use the following command to add something to the cupboard below the sink…

考虑到数组从索引0开始的事实,我们可以使用以下命令在水槽下方的橱柜中添加一些内容…

kitchen.addToCupboard(0, "cleaning spray")

结论 (Conclusion)

There is a lot more to learn about objects than I’ve covered here, but hopefully this helps you understand the basic principals of how objects work in JavaScript.

关于对象的知识比我在这里要介绍的要多得多,但是希望这可以帮助您了解对象如何在JavaScript中工作的基本原理。

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/javascript-basics-objects-object-manipulation-82fc9d39db06

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值