开发者

Javascript: Is there a keyword for referring to the current node in an object?

开发者 https://www.devze.com 2023-02-10 16:47 出处:网络
Consider the following code: function Animal(){ this.type = \"dog\"; this.color = { stomach: \"white\", paws: \"brown\",

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开发者_如何学Go 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?


Did you try running your code? Because this actually does refer to the color and not the Animal object.

This is how it works: this refers to whatever object the function was called upon, and under normal circumstances, your face function would be called as someAnimal.color.face() -- in this case, this already refers to the color object, so this.color would be an error while this.stomach would actually work.


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";
            }
        }
   });
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号