Javascript:是否有关键字用于引用对象中的当前节点?
考虑下面的代码:
function Animal(){
this.type = "dog";
this.color = {
stomach: "white",
paws: "brown",
face: function(){
if(this.color.stomach === "white"){
return "red";
}else{
return "blue";
}
}
}
这只颜色奇怪的狗的面部颜色取决于他胃的颜色。我想知道是否有一种语法上更简单的方法来编写“this.color.stomach”部分。即,“this”指的是主要 Animal 对象。是否有类似的关键字引用调用该关键字的父对象?例如,由于我已经在 Animal.color 中,因此不必重复该部分来获取其胃颜色(Animal.color.stomach),有没有一种方法可以直接引用颜色属性,以便它是就像“parent.stomach”,其中“parent”指的是它在其中被调用的任何属性 - 在本例中是 Animal.color?
Consider the following code:
function Animal(){
this.type = "dog";
this.color = {
stomach: "white",
paws: "brown",
face: function(){
if(this.color.stomach === "white"){
return "red";
}else{
return "blue";
}
}
}
This strangely colored dog has a face color that depends on the color of his stomach. I'm wondering if there is a more syntactically simple way of writing the "this.color.stomach" part. I.e., "this" refers to the main Animal object. Is there a similar keyword that refers to the parent object in which that keyword is called? For example, since I'm already inside Animal.color, rather than having to repeat that part to get at its stomach color (Animal.color.stomach), is there a way to directly reference the color property, so that it would be like "parent.stomach" where "parent" refers to whatever property it's being called within--in this case, Animal.color?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试运行您的代码吗?因为
this
实际上确实引用了color
而不是Animal
对象。它的工作原理如下:
this
指的是调用该函数的任何对象,在正常情况下,您的face
函数将被称为someAnimal.color。 face()
- 在这种情况下,this
已经引用了color
对象,因此this.color
将是一个错误而this.stomach
实际上可以工作。Did you try running your code? Because
this
actually does refer to thecolor
and not theAnimal
object.This is how it works:
this
refers to whatever object the function was called upon, and under normal circumstances, yourface
function would be called assomeAnimal.color.face()
-- in this case,this
already refers to thecolor
object, sothis.color
would be an error whilethis.stomach
would actually work.