Sophia Lee
Sophia Lee

Reputation: 37

setting properties using this keyword in a function

I am practicing makerjs with javascript. While I was using, I am having an issue with this keyword.

//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);

I don't understand how this code works. After saving with this keyword like bellow,

 this.paths = pathObject;

How can this works without returning anything?

Upvotes: 1

Views: 43

Answers (1)

Sumedh Chakravorty
Sumedh Chakravorty

Reputation: 385

Your myModel function doesn't need to return anything necessarily, it can also expose properties via this. makerjs.exporter.toSVG is looking for paths property on new myModel() instance which you have exposed in the line below.

this.paths = pathObject;

In the above line you are creating a property paths on your current instance, where current instance is accessed via this. As you can see in the snippet below i can access paths using m.paths.

You can read more about how this behaves when a function is called as a constructor here (look for '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)

Upvotes: 1

Related Questions