Advertisement
Guest User

Untitled

a guest
Jul 4th, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. // function pattern
  2. var myFunction = function(){return 'foo'};
  3. console.log(myFunction()); // log 'foo'
  4.  
  5. // method pattern
  6. var myObject = {myFunction: function(){return 'bar';}}
  7. console.log(myObject.myFunction()); // log 'bar'
  8.  
  9. // constructor pattern
  10. var Cody = function(){
  11. this.living = true;
  12. this.age = 33;
  13. this.gender = 'male';
  14. this.getGender = function() {return this.gender;};
  15. }
  16. var cody = new Cody(); // invoke via Cody constructor
  17. console.log(cody); // logs cody object and properties
  18.  
  19. // apply() and call() pattern
  20. var greet = {
  21. runGreet: function(){
  22. console.log(this.name,arguments[0],arguments[1]);
  23. }
  24. }
  25.  
  26. var cody = {name:'cody'};
  27. var lisa = {name:'lisa'};
  28.  
  29. //invoke the runGreet function as if it were inside of the cody object
  30. greet.runGreet.call(cody,'foo','bar'); //logs cody
  31.  
  32. //invoke the runGreet function as if it were inside of the lisa object
  33. greet.runGreet.apply(lisa, ['foo','bar']); //logs lisa
  34.  
  35. /* Notice the difference between call() and apply() in how parameters are sent to the function being invoked */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement