我练习makerjs
用javascript
。在使用时,this
关键字出现问题。
//render a model created by a function, using the 'this' keyword
var makerjs = require('makerjs');
function myModel() {
var line = {
type: 'line',
origin: [0, 0],
end: [50, 50]
};
var circle = {
type: 'circle',
origin: [0, 0],
radius: 50
};
var pathObject = { myLine: line, myCircle: circle };
//set properties using the "this" keyword ***here I dont' understand
this.paths = pathObject;
}
//note we are using the "new" operator
var svg = makerjs.exporter.toSVG(new myModel());
document.write(svg);
我不明白这段代码是如何工作的。使用以下关键字(例如波纹管)保存后,
this.paths = pathObject;
如何不返回任何东西?
您的myModel
函数不需要一定返回任何值,它还可以通过公开属性this
。makerjs.exporter.toSVG
正在寻找您在下面的行中公开的实例的paths
属性new myModel()
。
this.paths = pathObject;
在上一行中,您正在paths
当前实例上创建一个属性,可通过访问当前实例this
。如您在下面的代码段中所见,我可以使用paths
进行访问m.paths
。
您可以在此处详细了解有关this
将函数作为构造函数调用时的行为方式(查找“作为构造函数”)
function myModel() {
var line = {
type: 'line',
origin: [0, 0],
end: [50, 50]
};
var circle = {
type: 'circle',
origin: [0, 0],
radius: 50
};
var pathObject = { myLine: line, myCircle: circle };
//set properties using the "this" keyword ***here I dont' understand
this.paths = pathObject;
}
let m = new myModel();
console.log(m.paths)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句