1
var Foo = function() {
    this.message = "Hi";
}
Foo.prototype = {
    say: {
        hi: function() {
            console.log(this.message);
        }
    }
}

[edit]I know "this" in hi() refers say, is there any way to achieve this?

var he = new Foo();
he.say.hi(); //"Hi" to console
tosin
  • 1,159
  • 7
  • 14
  • 1
    Actually `this` in that context refers to the `say` object. If you add `this.say.message = "Hi";` to the constructor function your `console.log` call will log "Hi". – Ram Mar 04 '15 at 12:08
  • To achieve `this` or `what`? – Jonathan Mar 04 '15 at 12:10
  • possible duplicate of [javascript - accessing private member variables from prototype-defined functions](http://stackoverflow.com/questions/436120/javascript-accessing-private-member-variables-from-prototype-defined-functions) – Alex Char Mar 04 '15 at 12:25
  • @tosin Does this suits your requirement.. http://jsfiddle.net/Lz7fvcju/ – Rakesh_Kumar Mar 04 '15 at 12:35
  • @Vohuman Yes, my mistake. I fixed the question to avoid confusion. thanks – tosin Mar 04 '15 at 12:56
  • @AlexChar Thanks for reference but I don't think so. I just want to know structure variations(or the possibility) to write as "instance.property.method". – tosin Mar 04 '15 at 13:04
  • @Rakesh_Kumar Sorry for bad explanation. I want to write "instance.foo.method()". – tosin Mar 04 '15 at 13:06

2 Answers2

0

You can access like this.

var Foo = function(){
  this.par = 3;

  this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
    this.p = t;
    this.subFunction = function(){
      alert(this.p.par);
    }
  })(this);
}

var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;

myObj.par = 5;
myObj.sub.subFunction()
Bala.Raj
  • 1,011
  • 9
  • 18
0

All you need is to bind the hi function just like this:

var Foo = function() {
    this.message = "Hi";
    this.say.hi = this.say.hi.bind(this);
}
Foo.prototype = {
    say: {
    hi: function() {
        console.log(this.message);
        }
    }    
}

var he = new Foo();
he.say.hi();
Itay Merchav
  • 954
  • 8
  • 8