在函数中使用 this 关键字设置属性

setting properties using this keyword in a function

我正在用 javascript 练习 makerjs。 在我使用时,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 函数不一定需要 return 任何东西,它还可以通过 this 公开属性。 makerjs.exporter.toSVG 正在 new myModel() 实例上寻找 paths 属性,您在下面的行中公开了该实例。

this.paths = pathObject;

在上面的行中,您在当前实例上创建了一个 属性 paths,当前实例通过 this 访问。正如您在下面的代码片段中看到的,我可以使用 m.paths.

访问 paths

您可以阅读更多有关 this 将函数作为构造函数调用时的行为 here(查找 'As a constructor')

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)