How can i pass the context of
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 in the return will give context not as in (1) How can i access 1 in the return ?
You have to bind the function with the current object, with Function.prototype.bind
, like this
this.line = d3.svg.line()
.interpolate("linear")
.x(function (d) {
return this.x(d.x);
}.bind(this))
Since the anonymous function is bound to the current object this
, inside the function, this
refer to the actual this
bound.
The other common way is to retain the this
object, like 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`
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.