Javascript 在函数中使用此关键字设置属性
我正在用Javascript 在函数中使用此关键字设置属性,javascript,html,this,Javascript,Html,This,我正在用javascript练习makerjs。 在使用时,我对这个关键字有问题 //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 circ
javascript
练习makerjs
。
在使用时,我对这个
关键字有问题
//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
正在查找您在下一行中公开的new myModel()
实例上的path
属性
this.paths = pathObject;
在上面的一行中,您正在当前实例上创建一个属性path
,其中当前实例通过this
访问。正如您在下面的代码片段中看到的,我可以使用m.paths
访问路径
您可以阅读更多有关函数作为构造函数调用时此
的行为的信息(查找“作为构造函数”)
函数myModel(){
变量行={
键入:“行”,
来源:[0,0],
完:[50,50]
};
变量圆={
键入:“圆”,
来源:[0,0],
半径:50
};
var pathObject={myLine:line,myCircle:circle};
//使用“this”关键字设置属性***这里我不明白
this.path=pathObject;
}
设m=newmymodel();
console.log(m.path)
我完全理解。非常感谢你