Link to an object from a great child?

Let's say I have an object:

var person= {
      firstName:"Renzo",
      getFirstName:function(){
        console.log(this);// is the person object
        return this.firstName;
      },
      address:{
        number:function(){
          console.log(this);// is the number function
          //return person.getFirstName(); // it is working
          return this.firstName;// not working           
        }
      }       
   };
   
console.log(person.getFirstName());   
console.log(person.address.number());   
Run codeHide result

I know that the "this" in the getFirstName method refers to the person object, but the "this" in the number method will not refer to the person object, refers to the number .. function, I can access the getFirstName method from the number function referencing the object person who will solve the problem, but ...

Question: Is there a way to refer to a person object from a number method? without using a human variable ... is there any special keyword, such as "this", to access the person method?

+4
source share
4 answers

You can use ES6 classes and arrow functions to achieve this.

class Person {
    constructor() {
        this.firstName = "Renzo";
        this.address = {
            getNumber: () => this.firstName
        }
  }

  getFirstName() {
    return this.firstName;
  }
}

var person = new Person();
console.log(person.address.getNumber());

- https://jsfiddle.net/sgsvenkatesh/qtg1s2f2/1/

, . , .

+1

, , - :

var person = {
  firstName: 'Renzo',
  getFirstName() {
    return this.firstName;
  },
  address: {
    number: function() {
      return this.firstName;
    }
  }
}

// then call it
person.address.number.call(person); // 'Renzo'
+2

You can create an address so that it has access to its parent object:

function Person(n){
 this.firstName=n;
 this.address=new Adress(this);
}
Person.prototype= {
  firstName:"Renzo",
  getFirstName:function(){
    console.log(this);// is the person object
    return this.firstName;
  }
};

function Address(p){
 this.parent=p;
}
Address.prototype={
   number:function(){
      console.log(this);// is the number
      console.log(this.parent);//the parent
      return this.parent.getFirstName(); // it is working      
    }
 };

USECASE:

console.log((new Person("Me")).address.number());
+1
source

You can use it like this:

      var person= {
      firstName:"Renzo",
      getFirstName:function(){
        return this.firstName;
      },
      address:{
        number:function(){
          return person.firstName;
        }
      }       
   };


console.log(person.address.number()); 
0
source

Source: https://habr.com/ru/post/1680416/


All Articles