Javascript:如何将'this'设置为对象方法

时间:2015-03-30 12:44:37

标签: javascript

如何访问进入如下函数的对象中的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());
    };
}

2 个答案:

答案 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());
    };
}