dev   152726

« earlier    

Summary of the rules for the binding of `this` in JavaScript
1. Implicit Binding

Occurs automatically and implicitly when a function is called as a method of an object.
this points to the object to the left of the dot.
Most common and useful rule, ~80% of the cases.
let me = { name: "Mauro", sayName: sayName };

function sayName () {
console.log("Hello, my name is", this.name)
}

me.sayName(); // Hello, my name is Mauro
2. Explicit Binding

The easiest to spot because it's explicitly written by a programmer.
Done with .call, .apply and .bind
let me = { name: "Mauro" };
function sayName () {
console.log("Hello, my name is", this.name)
}

sayName.call(me) // Hello, my name is Mauro

var sayMauro = sayName.bind(me);
sayMauro(); // Hello, my name is Mauro
Can override implicit binding
let me = { name: "Mauro" };

function sayName () {
console.log("Hello, my name is", this.name)
}

let boundSayName = sayName.bind(me);

let you = { name: "Ann", sayName: boundSayName };

you.sayName(); // Hello, my name is Mauro
3. New Binding

Inside a function that was called with the new operator.
this points to the new object being created.
function sayName () {
console.log("Hello, my name is", this.name)
}

function Person (name) {
/
javascript  dev  web  this 
13 hours ago by adie_codes

« earlier    

related tags

$kippt_bookmark  %stack_overflow  5%  active_record  agile  ai  analysis  analytics  android  androiddev  apache  api  app  architecture  article  articles  auto  automation  aws  b2  backend  bitcoin  blackboard  blog  book  bookmarked_on_site  bootcamps  brew  charting  chartjs  chrome  cli  cloud  cms  code  codekit  coding  compsci  computing  css  data  database  databases  datastructure  design  devel  development  digital  django  dotfiles  electron  eslint  evaluation  extension  fonts  frontend  functional  git  glove  go  golang  gradient  gres  guidelines  haskell  hexagonal  history  howto  https  hype  icons  ilooklikeanengineer  import  in-depth  installation  ios  ito  javascript  js-fetch  js  json  kb  lang:js  learn  learning  linux  lists  logs  machine-learning  macos  mobile  mysql  news  nginx  node  npm  ocean  office  opensource  ops  optimizing  oracle  osx  packages  performance  photos  php-fpm  plugin  politics  post  postgres  postgressql  pricerules  pricing  programming  python  r  rails  react  redux  reference  repos  resources  sammlung  security  servers  setup  shrinkray  site  slack  slide  software  sql  ssventures  stack-overflow  stackoverflow  static  sysadmin  testing  this  tips  tool  tools  tuning  tutorial  ui  umn  vi  vim  web  webdesign  webdev-design  webdev  website  woo  word2vec  wordpress  work  workflow   

Copy this bookmark:



description:


tags: