Javascript:是否有用于引用对象中当前节点的关键字?
考虑以下代码:Javascript:是否有用于引用对象中当前节点的关键字?,javascript,object,this-keyword,Javascript,Object,This Keyword,考虑以下代码: function Animal(){ this.type = "dog"; this.color = { stomach: "white", paws: "brown", face: function(){ if(this.color.stomach === "white"){ return
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.gast”部分。也就是说,“this”指的是主要的动物对象。是否有一个类似的关键字引用调用该关键字的父对象?例如,由于我已经在Animal.color中,而不必重复该部分来获得它的胃颜色(Animal.color.gastry),有没有一种方法可以直接引用color属性,这样它就像“parent.gastry”,其中“parent”指的是它在其中被调用的任何属性——在本例中,Animal.color?是否尝试运行代码?因为
这个
实际上指的是颜色
,而不是动物
对象
这就是它的工作原理:
此
引用函数调用的任何对象,在正常情况下,面
函数将被称为someAnimal.color.face()
——在这种情况下,此
已经引用了颜色
对象,所以this.color
将是一个错误,而this.gast
将实际工作。。我正要说同样的话。谢谢,我想应该是这样的。我的问题是如何测试它。
function Color(data) {
this.stomach = data.stomach;
this.face = data.face;
}
function Animal() {
var self = this; // self now refers to the animal
this.type = "Dog";
this.color = new Color({
face: function() {
// in the "face" function, "this" refers to the color
if (this.stomach === "white") { // color's stomach
return "red";
} else if (self.type === "Dog") { // animal's type
return "Blue";
}
}
});
}