What _: and _

Asked

Viewed 1,332 times

4

What does _: and _. mean in the definition of functions as in the example below.

constructor(){
  router.events.subscribe((_:NavigationEnd) => this.currentUrl = _.url);
}

I have many doubts about.

1 answer

9


The underscore (_) is a variable. The point after it means that it is an object and is being accessed one of its properties

let _ = {
  foo: 'bar',
  baz: v => `foo bar baz ${v}`
}

console.log(_)
console.log(_.foo)
console.log(_.baz('taz'))

As quoted in comments by @Hebertdelima, Underscore.js uses this character as a "parent object" containing the functions and values of the library

The underscore too habitually (is a convention, not an obligation) to be used for private properties and functions of an object:

function Foo(_bar) {
  this.setBar = (bar) => { _bar = bar  }
  this.getBar = ()    => { return _bar }
}

let baz = new Foo('taz')
console.log(baz._bar)
console.log(baz.getBar())

In Typescript, the colon (:) indicates to which type this variable should be:

let foo :string //Tipo string

interface Baz {
  let taz :boolean; //Baz é um objeto com uma propriedade taz, do tipo booleana
}

let bar :Baz //Tipo Baz 
  • usually used for private properties and functions of an object. I think it would be interesting to point out that the _ in private functions is not a standard nomenclature, nor an obligation, it is only a convention that some people use, and that every day more is being adopted

  • Yeah, like I said, habitually, plus the frameworks and libraries that do this, I edited the question reinforcing this idea, thanks for the tip @Marceloboni

Browser other questions tagged

You are not signed in. Login or sign up in order to post.