将此指针嵌套在 javascript
nested this pointer in javascript
我正在使用 draw2d js 库。我有以下代码在 canvas.
上创建一个矩形
var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
rect.on("click", function(){
//var that = this;
alert("test");
// I'm trying to access rect using this keyword but its not working
var c = new draw2d.Connection();
this.createPort('hybrid'); // adds a port on the rectangle
});
我正在尝试使用此关键字访问 rect,但它不起作用
谢谢!
this
在该上下文中不是指 rect
,而是指您提供给 on
:
的匿名函数
function(){
alert("test");
var c = new draw2d.Connection();
this.createPort('hybrid'); // adds a port on the rectangle
} // => This is what `this` refers to.
直接引用rect
即可:
var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
rect.on("click", function(){
alert("test");
var c = new draw2d.Connection();
rect.createPort('hybrid'); // adds a port on the rectangle
});
this
是 JavaScript 的一个相当棘手的点。我建议阅读 Mozilla's guide 以更好地理解它。
我正在使用 draw2d js 库。我有以下代码在 canvas.
上创建一个矩形 var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
rect.on("click", function(){
//var that = this;
alert("test");
// I'm trying to access rect using this keyword but its not working
var c = new draw2d.Connection();
this.createPort('hybrid'); // adds a port on the rectangle
});
我正在尝试使用此关键字访问 rect,但它不起作用
谢谢!
this
在该上下文中不是指 rect
,而是指您提供给 on
:
function(){
alert("test");
var c = new draw2d.Connection();
this.createPort('hybrid'); // adds a port on the rectangle
} // => This is what `this` refers to.
直接引用rect
即可:
var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
rect.on("click", function(){
alert("test");
var c = new draw2d.Connection();
rect.createPort('hybrid'); // adds a port on the rectangle
});
this
是 JavaScript 的一个相当棘手的点。我建议阅读 Mozilla's guide 以更好地理解它。