如何在原型中访问变量

时间:2014-04-30 09:12:50

标签: javascript d3.js closures

我如何传递

的上下文
   Test = function(){
    this.x = //(1) How to access this in the return ?

    this.line = d3.svg.line()
        .interpolate("linear")
        .x(function (d) {
            return this.x(d.x);
        })

 }
回复中的this.x将给出上下文,而不是(1) 我怎样才能在回报中获得1?

1 个答案:

答案 0 :(得分:2)

您必须使用Function.prototype.bind将函数与当前对象绑定,就像这样

this.line = d3.svg.line()
    .interpolate("linear")
    .x(function (d) {
        return this.x(d.x);
    }.bind(this))

由于匿名函数绑定到当前对象this,因此在函数内部this引用实际的this边界。

另一种常见的方法是保留this对象,就像这样

Test = function() {
    var that = this;               // Retain the value of `this`
    this.x = 1;

    this.line = d3.svg.line()
        .interpolate("linear")
        .x(function(d) {
            return that.x(d.x);    // Use `that`, instead of `this`
        })
}
相关问题