var Foo = function() {
this.message = "Hi";
}
Foo.prototype = {
say: {
hi: function() {
console.log(this.message);
}
}
}
[编辑]我知道"这个"在hi()中指的是,有没有办法实现这个目标?
var he = new Foo();
he.say.hi(); //"Hi" to console
答案 0 :(得分:0)
您可以像这样访问。
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()
答案 1 :(得分:0)
你只需要像这样绑定hi函数:
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();