Posts mit dem Label code werden angezeigt. Alle Posts anzeigen
Posts mit dem Label code werden angezeigt. Alle Posts anzeigen

Freitag, 17. Februar 2012

No need for temporary variable (Javascript)

Assume you have a function, and that function has a param (called 'config' herein) which may be a string or an object. Inside your function, you check for the type and if it's a string, you want to make this strings value a property of your object.

My first, fast approach was this one:
var url = config;
config  = {};
config.videoLink = url;

My second approach looked like this:
var url = config;
config  = {videoLink: url};

I thought about what's happening in those statements and realized that the temporary variable 'url' is not needed, because javascript is executing the assignement from right to left, means I can override 'config' with an object that keeps the original value of config as a property. See this third & final approach:
config = {videoHash: config};

So Javascript builds the object, assigns the value of config (string) to videoHash and assigns this object to config, which now is a object as desired.

Donnerstag, 25. August 2011

Coding Backwards

Now this is a really cool idea how to get a gerneral idea of the design you really need (and this is NOT the design that comes to your mind FIRST):

"I decided that I’d [...] write out a script using the yet unwritten API. I’d reverse-engineer a good design by pretending I’d already written one!"

"A better design quickly appeared when I forced myself to preemptively eat my own dogfood. Instead of shoehorning use-cases into a class structure I’d already designed, I coded backwards and the opposite happened: a design evolved from daydreaming about an API that I’d like using."

SOURCE: http://jameso.be/2011/08/19/coding-backwards.html



Samstag, 23. Juli 2011

JS Module Pattern

var someModule = (function(){
//private attributes
  var privateVar = 5;

  //private methods
  var privateMethod = function(){
  return 'Private Test';
  };

  return {
    //public attributes
    publicVar: 10,
    //public methods
    publicMethod: function(){
      return ' Followed By Public Test ';
    },

    //let's access the private members
    getData: function(){
      return privateMethod() + this.publicMethod() + privateVar;
    }
  }
})(); //the parens here cause the anonymous function to execute and return
        
someModule.getData();
SOURCE: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Mittwoch, 15. Juni 2011

Javascript OOP Cheatsheet

var MyClass = function() {

    // self to get "this" in private / global / anonymous methods
    var self = this;

    // public var
    this.publicVar = 'public';
    // private var
    var privateVar = 'private';

    // public method
    this.publicMethod = function() {}
    // private method
    function privateMethod() {}
    // global method
    globalMethod = function() {}

}