<?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; prototype</title>
	<atom:link href="http://www.jslog.com/tag/prototype/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>No for loops &#8211; Number prototype instead</title>
		<link>http://www.jslog.com/loop-using-number-prototype</link>
		<comments>http://www.jslog.com/loop-using-number-prototype#comments</comments>
		<pubDate>Fri, 26 Nov 2010 17:19:02 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[function scope]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=233</guid>
		<description><![CDATA[Recently I got borred with the for loops and I added the &#8220;times&#8221; function on the prototype of Number. As a result, I can easily iterate over arrays or I can simply call a function how many times I want like this:

     (5).times(function(index /* zero based */){
     [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I got borred with the for loops and I added the &#8220;times&#8221; function on the prototype of Number. As a result, I can easily iterate over arrays or I can simply call a function how many times I want like this:</p>
<pre class="prettyprint">
     (5).times(function(index /* zero based */){
           console.log(index);
     })
     //or using array length
     arr.length.times(function(){ ... });

     //optionally specify scope for the callback function:
    n.times(function(){ .... }, scope);
</pre>
<p>Together with this, I&#8217;m using another goodie. Whenever I have a function that expects a parameter which can either be a simple value or an array, convert that value to array in one line, like: </p>
<pre class="prettyprint">
    var arr = [].concat(valueOrArray);
</pre>
<p>See below the source code.</p>
<pre class="prettyprint">/**
 * extend the Number prototype
 * @param func
 * @param scope [optional]
 */
Number.prototype.times = function(func, scope){
    var v = this.valueOf();
    for (var i=0; i < v; i++){
        func.call(scope||window,i);
    }
};

function test(valueOrArray){
    var arr = [].concat(valueOrArray)
    arr.length.times(function(i){
        console.log(arr[i]);
    })
}

test([1,3,4])
//output: 1   3   4

test(123)
//output: 123</pre>
<p>As for the performance, I have tested the <b>times</b> function against the for loop, and it seems to give about same results at a first glance. Any feedback on this?</p>
<p>P.S. Iterating over arrays gets even easier by adding an <b>'each'</b> function to the Array prototype. Adding to the prototype of standard JavaScript objects is a debatable practice, and should not be abused.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/loop-using-number-prototype/feed</wfw:commentRss>
		<slash:comments>2</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>ExtJS TextField that cannot start with whitespace</title>
		<link>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace</link>
		<comments>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace#comments</comments>
		<pubDate>Thu, 01 Apr 2010 11:43:32 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[ExtJS Components]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[overriding]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[textfield]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=192</guid>
		<description><![CDATA[Recently I needed a text field in ExtJS that doesn&#8217;t allow user input to start with space. So I thought it would be useful for others as well. I chose to override the original Ext.form.TextField and make all the textfields in the application have this behaviour.
Here is the code for this:

(function(){
    //put [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I needed a text field in ExtJS that doesn&#8217;t allow user input to start with space. So I thought it would be useful for others as well. I chose to override the original Ext.form.TextField and make all the textfields in the application have this behaviour.</p>
<p>Here is the code for this:</p>
<pre class="prettyprint">
(function(){
    //put all the code in an anonymous function to hide the local variables from the global namespace

    //methods that will be overriden - keep the original
    var originalFilterKeys = Ext.form.TextField.prototype.filterKeys;
    var originalInitEvents = Ext.form.TextField.prototype.initEvents;

    Ext.override(Ext.form.TextField,{

        // private
        filterKeys : function(e){
            var res = originalFilterKeys.apply(this, arguments);

            var cc = String.fromCharCode(e.getCharCode());

            //if the caret is in the first position, and the typed character
            //was space, stop the event
            if (cc == ' ' &#038;&#038; (this.getCaretPos(this.el.dom) == 0) ){
                e.stopEvent()
            }

            //the case when the text is selected and the user presses space
            if (cc == ' ' &#038;&#038; this.getSelectedText() == this.getValue()){
                //clear value of the text field
                e.stopEvent();
                this.setValue('');
            }

            return res; //return original result
        },

        /**
         * @return String the selected text or '' if none
         */
        getSelectedText: function(){
            var dom = this.el.dom;
            var selected = (dom.value).substring(this.getSelectionStart(), this.getSelectionEnd());

            return selected;
        },

        getSelectionStart: function(){
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionStart;
            } else if (document.selection) { // IE
                var pos, textRange = document.selection.createRange().duplicate();

                if (textRange.text.length > 0) { // selection is not collapsed
                    pos = input.value.indexOf(textRange.text);
                } else { // selection is collapsed
                    pos = 0;
                }

                return pos;
            }
            return 0;
        },

        getSelectionEnd: function() {
            var input = this.el.dom
            if (input.setSelectionRange){ // Mozilla
                return input.selectionEnd;
            } else if (document.selection) { // IE
                var selectedRange = document.selection.createRange().duplicate();
                if (selectedRange.text.length > 0){
                    selectedRange.moveStart("character", -input.value.length);
                }
                return selectedRange.text.length;
            }

            return 0;
        },

        /**
         * @return int - the current index of the caret
         */
        getCaretPos: function() {
            var input = this.el.dom;
            var pos = 0;
            if (input.createTextRange) {
                var range = document.selection.createRange().duplicate();
                range.moveStart('textedit',-1);
                pos = range.text.length;
            } else if (input.setSelectionRange) {
                pos = input.selectionEnd;
            }
            return pos;
        },

        // private
        initEvents : function(){
            this.maskRe = new RegExp('.*'); //I just needed a reg exp to match all characters
            //as filterKeys method is only called if the textfield has a 'maskRe' property
            return originalInitEvents.call(this);
        }
    })

})()
</pre>
<p>Hope it helps! Enjoy the code. If you have any questions, let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/extjs-textfield-that-cannot-start-with-whitespace/feed</wfw:commentRss>
		<slash:comments>4</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>
	</channel>
</rss>

