<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>A Log on JavaScript &#187; functions</title>
	<atom:link href="http://www.jslog.com/category/functions/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jslog.com</link>
	<description></description>
	<lastBuildDate>Thu, 21 Jul 2011 11:00:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Delayed function execution</title>
		<link>http://www.jslog.com/delayed-function-execution</link>
		<comments>http://www.jslog.com/delayed-function-execution#comments</comments>
		<pubDate>Thu, 21 Jul 2011 11:00:10 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[delayed]]></category>
		<category><![CDATA[function execution]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=265</guid>
		<description><![CDATA[I have written a small helper function to make delayed sequential function execution easier.
We have the following case: we need to execute an array of functions. The second one has to execute after the first one finishes, the third after the second and so one. The scenario gets a bit more complicated when wee need [...]]]></description>
			<content:encoded><![CDATA[<p>I have written a small helper function to make delayed sequential function execution easier.</p>
<p>We have the following case: we need to execute an array of functions. The second one has to execute after the first one finishes, the third after the second and so one. The scenario gets a bit more complicated when wee need some delay between functions. So we have to execute function 1, then after it finishes, wait for 200 ms, and execute function 2, then after another 500 ms execute function 3 and so on.</p>
<p>So the code is the following:</p>
<pre class="prettyprint">
function runSequence(arr, scope, delay){
	arr.push(function(){});
	delay = delay || 0;

	var i = 0,
             len = arr.length;

	for(;i &#60; len-1; i++){
		(function(index, thisObject){
			arr[index] = function(){
				var isFn = !!thisObject.call,
					fn = isFn? thisObject : thisObject.fn,
					fnScope = isFn? scope: thisObject.scope,
					fnDelay = isFn? delay : thisObject.delay,
					fnToExecute = function(){ fn.call(this); arr[index+1](); }

                                fnScope = fnScope || this;
				fnDelay? setTimeout(function(){ fnToExecute.call(fnScope) }, fnDelay) : fnToExecute.call(fnScope);
			}
		})(i, arr[i]);
	}

	arr[0]();
}
</pre>
<p>We can do the following:</p>
<pre class="prettyprint">
runSequence([
	{ fn: function(){ console.log('executed immediately') }, delay: 0 },
	{
          fn: function(){ console.log('this was after 1500 ms, with scope: ', this.name) },
          delay: 1500,
          scope: {name: 'sequence running'}
        },
	{ fn: function(){ console.log('this was after 2s ') }, delay: 2000 }
], this)
/*
 * The first and the last functions above are executed in the scope of the code executing the runSequence function
 * The second function is instead called with the scope being the passed object, {name: 'sequence running'}
 */
</pre>
<p>or the following:</p>
<pre class="prettyprint">
runSequence([
	function(){ console.log('first after 200ms') },
	function(){ console.log('yet another 200 ms') },
	function(){ console.log('the last fn at 200ms') }
], this, 200)
/*
 * A shorter form of the runSequence function call, with functions running at equal timeouts, in the passed 'this' scope
 */
</pre>
<p>This function can be useful when processing large amounts of data that would otherwise block the browser, or in cases when one would need to trigger ajax calls with a certain delay in between. I&#8217;m sure that there are other cases when this could prove useful.<br />
In the case of processing large amounts of data, one could use this to fill up a (non-paginated) grid with data, in chunks of, say, 200 records.</p>
<p>Do you find this pattern useful?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/delayed-function-execution/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Function arguments</title>
		<link>http://www.jslog.com/function-arguments</link>
		<comments>http://www.jslog.com/function-arguments#comments</comments>
		<pubDate>Mon, 31 May 2010 09:32:17 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=209</guid>
		<description><![CDATA[Well, if you are programming in JavaScript for a while, you are familiar with the arguments &#8216;array&#8217; which gives you access to function arguments by index, without the need of argument names. And if you are programming JavaScript for a bit longer while, you will know that arguments is not even a normal array. It [...]]]></description>
			<content:encoded><![CDATA[<p>Well, if you are programming in JavaScript for a while, you are familiar with the <b>arguments</b> &#8216;array&#8217; which gives you access to function arguments by index, without the need of argument names. And if you are programming JavaScript for a bit longer while, you will know that <b>arguments</b> is not even a normal array. It does not have any methods of an array. You can just use it to access items by index and also access it&#8217;s <b>length</b> property. That&#8217;s all. What if you want to make a copy of the array? What if you want to push or pop items? Well&#8230; you have some work to do&#8230; OR &#8230;</p>
<p>Or do something smart. Like call the slice method from Array.prototype on the arguments, something like:</p>
<pre class="prettyprint">
//this makes a copy of the arguments and returns a true array
Array.prototype.slice.call(arguments, 0) 

//pushes the value '5' in the arguments
Array.prototype.push(arguments, 5)
//this is not valid: arguments.push(5)
</pre>
<p>Well, maybe most of you expert JavaScript programmers have thought about this, and this is not a news. But, let&#8217;s share from our experience to the more novice/newcomers to JavaScript and show them the beauty of this language! </p>
<p>JavaScript is a great language! It&#8217;s expressive! It&#8217;s powerful! That&#8217;s why we love JavaScript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/function-arguments/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object oriented JavaScript with ExtJS</title>
		<link>http://www.jslog.com/object-oriented-javascript-with-extjs</link>
		<comments>http://www.jslog.com/object-oriented-javascript-with-extjs#comments</comments>
		<pubDate>Sat, 23 Jan 2010 20:49:47 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[object oriented javascript]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=97</guid>
		<description><![CDATA[This article explains how you can achieve powerful object oriented JavaScript with the help of ExtJS Core library. Good points on inheritance, overriding, flexibility, possible pitfalls that come with this approach. A good way to start building one page JavaScript web applications.]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been working a lot with ExtJS and I thought it&#8217;s good to share my experience. In this post I will explain how you can achieve object orientation with the help of <a href="http://www.extjs.com/products/extcore/?ref=family">ExtJS Core</a>, how easy it can be and some of its pitfalls.<span id="more-97"></span><strong> Learn by example</strong></p>
<pre class="prettyprint">
Ext.ns('myapp.cars');

(function(){
    var Car = Ext.extend(Object,{
	color: 'red',
	description: {
	    gears: 4,
	    year: 1980
	},

	constructor: function(config){
	    console.log("car constructor");
	    Ext.apply(this, config)
	},

	getColor: function(){
	    return 'actual color ' + this.color;
	},

	getMake: function(){
	    throw 'unimplemented method';
	}
    })

    myapp.cars.Car = Car;
})()

// ---- another file here: myapp.cars.Bmw.js
Ext.ns('myapp.cars');

(function(){

    var BmwCar = Ext.extend(myapp.cars.Car,{

	color: 'blue',

	constructor: function(config){
	    BmwCar.superclass.constructor.apply(this, arguments)
	},

	getMake: function(){
	    return "This is a BMW"
	}
    })

    myapp.cars.Bmw = BmwCar;
})()
</pre>
<p>First of all notice</p>
<pre class="prettyprint">
(function(){
     // your code here
})()
</pre>
<p>
We never want to populate our global &#8220;namespace&#8221; of JavaScript objects. So, we put all our code in a anonymous function, which is not only defined, but also executed. We will export only what&#8217;s needed, that is, the public API of our app.<br />
Second, notice</p>
<pre class="prettyprint">
Ext.ns('myapp.cars');
</pre>
<p>outside of our anonymous-function-that-hides-it-all. It is a shorthand for Ext.namespace. What it does is the following: it creates an object <code>myapp</code>, if it doesn&#8217;t exist. Then, it creates a property on this object (the newly created or the existing one) named <code>cars</code>, only if it doesn&#8217;t exist. I recomend putting a call to <code>Ext.ns('...')</code> at the beginning of every js file, and then, in the anonymous function call, attach what you need to into this public namespacing object. So all your files should look something like</p>
<pre class="prettyprint">
Ext.namespace('myapp.package.subpackage');
(function(){
    var MyClass = // class definition
    ....
    // end of class definition

    //in this way we "export" MyClass to be visible publicly
    myapp.package.subpackage.MyClass = MyClass
})()
</pre>
<p>Now let&#8217;s see our class hierarchy. Use <code>Ext.extend</code> to extend from an existing Object. If you don&#8217;t have a specific superclass you want to extend, just extend Object. Then, as a second parameter, provide an object literal, which can contain properties and/or functions. All these properties/functions will be placed in the prototype of your newly created class, overriding (if it is the case)  the properties in the prototype of the base class. Notice Ext has a special function, named <b>constructor</b>, which is called when objects are instantiated. If you define a constructor in the subclass, <b>don&#8217;t forget to call the superconstructor of the base class</b> (if you want &#8211; and probably you do).</p>
<pre class="prettyprint">
constructor: function(config){
   BmwCar.superclass.constructor.apply(this, arguments)
}
</pre>
<p>Notice how methods from the base class are called: &lt;current_class&gt;.superclass.&lt;method_name&gt;.apply(this, arguments). You could also call it with <b>call</b> and other arguments, but in this way, you just forward the existing arguments, whithout having to explicitly name them.<br />
In this example, in the constructor of the Car class we use a very powerful feature in JavaScript and ExtJS, dynamically applying properties to objects</p>
<pre class="prettyprint">
constructor: function(config){
    console.log("car constructor");
    Ext.apply(this, config)
},
</pre>
<p>Take all the properties given in the config and apply them to the car object. For instance, you could have a code like:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw({
	color:'black',
	getColor: function(){
	    return "my custom color";
	}
});
</pre>
<p>Not only does Bmw overrides the color attribute for the car, but this bmw instance in particular overrides the color attribute to &#8216;black&#8217;. Also override the <b>getColor</b> method. This gives a tremendous flexibility, allowing more than one level of overriding! Subclass overrides superclass, and object instance(of subclass) overrides subclass. So basically you can end up building custom bmw instances, each having it&#8217;s own implementation of getColor. Generally you won&#8217;t do method overriding at instance level, but you will want to override values in the properties of an instance. So calling your constructor with a config object is very useful when wanting to set values of multiple fields at once. </p>
<p>Another interesting feature is overriding a method at instance level, and also <b>using the previous implementation of the method</b>. Take a look:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw({
	color:'black',
	getColor: function(){
	    console.log('getColor: ');
            //use previous implementation - notice apply
	    return myapp.cars.Bmw.prototype.getColor.apply(bmw) + ' custom color';
	}
});
</pre>
<p>Notice the call to the <b>getColor</b> method from the prototype of the Bmw class, applied to the current instance, in order to keep the context of the method call.<br />
All these features of <b>prototypal inheritance</b> with JavaScript in general and ExtJS in particular, allow a great flexibility and many levels of customization.<br />
<br />
To recap, don&#8217;t forget that when you override a method, if you want to use the implementation in the base class, you have to use something like:</p>
<pre class="prettyprint">
 var BmwCar = Ext.extend(myapp.cars.Car,{
    getMake: function(){
        //use implementation in the superclass and forward any arguments
        BmwCar.superclass.getMake.apply(this, arguments)
    }
})
</pre>
<p>where <b>superclass</b> is a property set by <b>ExtJS</b> when creating the class, for easy reference to the superclass.</p>
<h2>Pitfalls</h2>
<p>There are some pitfalls you should be aware of. These appear because of the nature of the prototypal inheritance.<br />
Don&#8217;t forget that when you write:</p>
<pre class="prettyprint">
var subclass = Ext.extend(MySuperclass, {
    property1: value1,
    property2: value2,
    method1: function(){ ... },
    method2: function(){ ... }
});
</pre>
<p>all the properties of the config object given as the second argument to the <b>Ext.extend</b> function go into the prototype of the subclass. Let&#8217;s have some examples to see what can happen. Suppose for this example the myapp.cars.Car implementation above and the following Bmw implementation:</p>
<pre class="prettyprint">
var BmwCar = Ext.extend(myapp.cars.Car,{
	model: {
	    name: 'sedan'
	}
})
</pre>
<p>Now make the following tests:</p>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw();
var secondBmw = new myapp.cars.Bmw();

secondBmw.color = "orange";
secondBmw.model = { name: 'hatchback'}

//typical behavior
console.log(bmw.color); // outputs "red"
console.log(bmw.model); //outputs Object { name="sedan"}
</pre>
<pre class="prettyprint">
var bmw = new myapp.cars.Bmw();
var secondBmw = new myapp.cars.Bmw();

//NOTICE change of model name also affects the first bmw instance
secondBmw.model.name = 'hatchback'
console.log(bmw.model); //outputs Object { name="hatchback"}
</pre>
<p>So we modify the model.name attribute on the secondBmw and it gets propagated to the first bmw instance. Why? Well, the <b>model</b> object belongs to the prototype of the Bmw class, so <b>it is shared between all the bmw instances</b>. Any change in properties of this object affects all instances of the class!<br />
But notice in the first test, changing the <b>model</b> object doesn&#8217;t affect all instances of Bmw. This is because the instruction</p>
<pre class="prettyprint">
secondBmw.model = { name: 'hatchback'}
</pre>
<p>changes the <b>model</b> property on the secondBmw instance to refer to a whole new object, independent of the class prototype. <br />
So you have to be warned. It&#8217;s <b>okay to put in the prototype properties which are JavaScript primitive types</b> (strings, numbers), but you have to take <b>special care when dealing with objects</b>! They are allowed, but you should be aware of the facts explained above and handle with care.</p>
<p>This is a summary of prototypal JavaScript inheritance with ExtJS. Play with it, try it, use it!<br />
Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/object-oriented-javascript-with-extjs/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Intercepting function calls</title>
		<link>http://www.jslog.com/intercepting-function-calls</link>
		<comments>http://www.jslog.com/intercepting-function-calls#comments</comments>
		<pubDate>Mon, 28 Dec 2009 18:30:45 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[aspect oriented javascript]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=30</guid>
		<description><![CDATA[What is really fascinating about JavaScript is it's dynamic nature. You can dynamically change the behaviour of the code... even not your code. While this is really powerful, it can be also a pain if not used with care.]]></description>
			<content:encoded><![CDATA[<p>What is really fascinating about JavaScript is it&#8217;s dynamic nature. You can dynamically change the behaviour of the code&#8230; even not your code. While this is really powerful, it can be also a pain if not used with care.</p>
<p>
Well, let&#8217;s do something practical now. I want to intercept every log message in my js application. As people usually use Firebug (and if you&#8217;re not using it&#8230; well, you should, so <a href="http://getfirebug.com/">start right here</a>), the javascript code is populated with <code>console.log</code> or <code>console.warn</code> messages. Say we want to execute a function before and after <code>console.log</code> is called. Test the following code within firebug.
</p>
<p><pre class="prettyprint">
var backup = console.log;

function beforeLog(){
    backup('before log:',arguments);
}

function afterLog(){
    backup('after log:',arguments);
}

console.log = function(){
    beforeLog.apply(this,arguments);
    backup.apply(this,arguments);
    afterLog.apply(this,arguments);
}

console.log('hello','world');
</pre>
</p>
<p>
In the first place, make a backup to the function we want to intercept.<br/><br />
Second, just redefine the function&#8230; and we usually want to execute the old function (so here is where we need the backup) and perform some additional things as well. Placing the code at the beginning of your coolest app changes the behaviour of all the log messages you have.
</p>
<p>
I found this useful when going from a development environment to a live environment. The best choice would be to use a build system to comment out (or even better, delete) all the <code>console.log()</code> calls. But a quick fix when going live is the following:</p>
<pre class="prettyprint">
if (!window.console){
   /*
    * for users who do not have firebug installed,
    * just define a "mock" console object
    */
    window.console = {};
}
window.console.log = function(){};
console.log('hello world'); // call to an empty function
</pre>
</p>
<p>This is just a simple use of dynamically changing the behaviour of existing code. What about you? How do you intercept function calls? Waiting for some nice suggestions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/intercepting-function-calls/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

