Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在函数中使用此关键字设置属性_Javascript_Html_This - Fatal编程技术网

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)
我完全理解。非常感谢你