0

I'm relatively new to javascript, just digging through faker package I downloaded from npmjs.

The following is one of the method that I can call to generate a random color by calling the method like this: faker.commerce.color(). I get how the method works but I don't understand why it works.

This bit : var Commerce = function(faker) I find especially confusing, why don't you just make commerce an object, make a constructor with it and then call the function inside the object?. I've written the bit I find confusing in the code section below:

var Commerce = function (faker) {
var self = this; <------ *what is "this"? usually it should refer to the argument "faker" but looking down below seeing as you can call "commerce.color", self must equal to Commerce?*


self.color = function() {
  return faker.random.arrayElement(faker.definitions.commerce.color);
}; *<--- what is "self" referencing to here then?*

if Commerce = function(faker), by calling faker.commerce.color(), aren't you doing: faker.function(faker).color()?

kshatriiya
  • 209
  • 4
  • 12
  • To sum up: Your question is about `this` in Javascript? – DDMC Sep 18 '16 at 04:09
  • Yeah, pretty much, what is "this" referring to in this case? – kshatriiya Sep 18 '16 at 04:13
  • Asking about `this` in JavaScript is a trivial question that has been answered a hundred times before. Search your question before you post. – amallard Sep 18 '16 at 04:21
  • @amallard I generally understand the use of keyword "this", my question is very specific to this instance of code. This is because I wasn't aware of the idea of name spacing and function wrapper, which is what the above code is structured in. Everything put together came across as incredibly confusing to a novice like me. If the scope of this question is way below some expert like you, you can just not answer it, instead of trivialising without actually trying to see what I was asking. Some users on reddit have already answered my question, so at least thanks for dropping by. – kshatriiya Sep 18 '16 at 07:30
  • Here's the thread on reddit https://www.reddit.com/r/javascript/comments/53avez/var_v_functione_var_self_this_what_is_this_in/?st=it8aypvy&sh=d2669e48 – kshatriiya Sep 18 '16 at 07:30

0 Answers0