如何访问进入如下函数的对象中的this
:
function Foo (name) {
this.name = name;
var _ = {};
_.bar = {};
_.bar.print() = function () {
return this.name; // here I have access to the wrong this
};
this.print = function () {
console.log(_.bar.print());
};
}
答案 0 :(得分:2)
你可以做到
_.bar.print() = (function () {
return this.name;
}).bind(this);
但整体看起来毫无用处。
答案 1 :(得分:1)
只需将必需的this
保存到变量中,然后在其他范围内使用
function Foo (name) {
var _this = this; // <-- store function's this
this.name = name;
var _ = {};
_.bar = {};
_.bar.print() = function () {
return _this.name; // use stored _this
};
this.print = function () {
console.log(_.bar.print());
};
}