[英]How to access 'this' variable in a prototype function if it is overridden?
[英]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.