繁体   English   中英

如何在原型中访问变量

[英]How to access variable in prototype

我怎样才能通过上下文

   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?

你必须使用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`
        })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM