W
W
websiller2017-09-01 10:44:24
JavaScript
websiller, 2017-09-01 10:44:24

How to correctly refer from a child object to a parent object in javascript?

There is a code in which the child object refers to the parent in this way

function JClass() {
  this.v = 1;
};
JClass.prototype = {
  newo:function(){
    var t=this;
    return {
      readv:function(){alert(t.v)}
    }
  }
};

new JClass().newo().readv();

Question: What is the correct way to get to the this of the desired object from the returned one. For example, without using an intermediary (var t)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2017-09-01
@Casufi

https://github.com/getify/You-Don't-Know-JS

function JClass() {
  this.v = 1;
};
JClass.prototype = {
  newo:function(){
    return {
      readv:()=>{alert(this.v)}
    }
  }
};
new JClass().newo().readv();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question