• It's common to use adjectives as the names for decorator functions.

Decorator functions can pass in more than just simple value properties. They can also pass in functions.

  • "Functions in Python cannot be anonymous, and function declarations are not expressions, so they cannot be defined and used on the same line." (Helpful article: difference between javascript and python)
  • Tip: move functions outside of constructor function so that the function is not invoked every time an object is instantiated. For example:
var Car = function(obj, loc) { 
var obj = {loc: loc };
obj.move = move;
return obj;
}

var move = function() { 
    obj.loc++;
}
  • Decorators take in another function or a class as an argument and return a modified function or class.
  • The reason why most JS libraries are wrapped in an anonymous function: it protects the contents of the library from interference by other .js files.
  • In javascript, variable hoisting happens. That is, a variable is defined ("hoisted") to the top of its scope (e.g. if var a = 5 on line 5 inside a function, it would be as if var a; on line 2).

In python, there is no variable hosting, so an identifier would not exist until the interpreter reached the line of code where it was defined. (Source)


Q: How do I simply the following?

var amy = {loc: 1}
amy.loc++;
var ben = {loc: 1}
ben.loc++;

A:

var move = function(car) { 
   person.loc++;
}

var carlike = function(obj, loc) {
   obj.loc = loc;
   return obj;
}

var amy = carlike({}, 1);
var ben = carlike({}, 2);
move(amy);
move(ben);

==============

This post is a part of the #100daysofcode challenge.

blog comments powered by Disqus
  • Hi, I'm Linda! I enjoy going to tech meetups, learning web development, and blogging about the learning path. Follow me @LPnotes

Subscribe to The Coding Diaries