0

I have tried hard looking for a solution for this issue, found kind of strange that this question wasn't asked before here:

    var A = function(){
    this.timeLength = 5;
    }
    A.prototype.info = {
    type: 'video',
    duration: function(){ return this.timeLength;}
    }

    var AInst = new A();
    AInst.info.duration(); // is giving undefined

How to write this in the way to make it access the instance property?

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
  • You misspelled it. You wrote Ainst when the object is called AInst – shadymoses May 20 '17 at 21:53
  • 2
    No, `this` is referring to `AInst.info` - that's why it doesn't see `timeLength` – Bergi May 20 '17 at 21:55
  • 1
    [Don't try to do this](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance) – Bergi May 20 '17 at 21:56

2 Answers2

0

A couple of things here:

  1. Typo on AInst and duration.
  2. The this.timelength in your duration method is referring to A.prototype.info, not A.prototype

That being said, you could change your code by either invoking AInst.info.duration() on the last line, or just assign .type and .duration to A.prototype:

var A = function(){
  this.timeLength = 5;
}
A.prototype = {
  type: 'video',
  duration: function(){ return this.timeLength;}
}

var AInst = new A();
AInst.duration();
kqcef
  • 527
  • 1
  • 4
  • 17
0

'this' is wherever 'this' is called. so... function(){ this } 'this' is the function. You could use the window object. If needed, you can pass a 'this' as an argument to another function... just don't call it 'this'... that'll get ugly fast. 'self' is a common name for copies of a 'this'

window.onload = doThis;
function doThis() {
  var A = function(){
  window.timeLength = 5;
  }
  A.prototype.info = {
  type: 'video',
  duration: function(){ return window.timeLength;}
  }

  var AInst = new A();
  AInst.info.duration(); // is giving undefined

  console.log(AInst.info.duration());
}
admcfajn
  • 2,013
  • 3
  • 24
  • 32
  • Another option would be to define the timeLength variable outside the scope of either of those functions. So they could both access it. – admcfajn May 20 '17 at 22:22