It comes up very often. Should I use alias or alias_method . Let’s take a look at them in a bit detail.
Usage of alias
Usage of alias_method
First difference you will notice is that in case of alias_method we need to use a comma between the “new method name” and “old method name”.
alias_method takes both symbols and strings as input. Following code would also work.
That was easy. Now let’s take a look at how scoping impacts usage of alias and alias_method .
Scoping with alias
In the above case method “name” picks the method “full_name” defined in “Developer” class. Now let’s try with alias.
With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.
This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.
Overall my recommendation would be to use alias_method. Since alias_method is a method defined in class Module it can be overridden later and it offers more flexibility.
Function bindAll internally uses bind . And bind internally uses apply. So it is important to understand what apply does.
If I execute above code then I get [object window] is beautiful. I am getting that message because when function is invoked then this is window, the default global object.
In order to change the value of this we can make use of method apply as given below.
In the above case the alert message will be Internet is beautiful . Similarly following code will produce Beach is beautiful .
In short, apply lets us control the value of this when the function is invoked.
Why bind is needed
In order to understand why bind method is needed first let’s look at following example.
Above example is pretty straight forward. john is an instance of Developer and when says function is invoked then we get the right alert message.
Notice that when we invoked says we invoked like this john.says(). If we just want to get hold of the function that is returned by says then we need to do john.says. So the above code could be broken down to following code.
Above code is similar to the code above it. All we have done is to store the function in a variable called func. If we invoke this function then we should get the alert message we expected. However if we run this code then the alert message will be undefined rocks!.
We are getting undefined rocks! because in this case func is being invoked in the global context. this is pointing to global object called window when the function is executed. And window does not have any attribute called skill . Hence the output of this.skill is undefined.
Earlier we saw that using apply we can fix the problem arising out of this. So lets try to use apply to fix it.
Above code fixes our problem. This time the alert message we got was Ruby rocks!. However there is an issue and it is a big one.
We should try to create functions which can easily be called by the consumers of the function. This is where bind comes in.
How bind solves the problem
First lets see how using bind solves the problem.
To solve the problem regarding this issue we need a function that is already mapped to john so that we do not need to keep carrying john around. That’s precisely what bind does. It returns a new function and this new function has this bound to the value that we provide.
Here is a snippet of code from bind method
As you can see bind internally uses apply to set this to the second parameter we passed while invoking bind.
Notice that bind does not change existing function. It returns a new function and that new function should be used.
How bindAll solves the problem
Instead of bind we can also use bindAll . Here is solution with bindAll.
Above code is similar to bind solution but there are some big differences.
The first big difference is that we do not have to worry about the returned value of bindAll . In case of bind we must use the returned function. In bindAll we do not have to worry about the returned value but it comes with a price. bindAll actually mutates the function. What does that mean.
See john object has an attribute called says which returns a function . bindAll goes and changes the attribute says so that when it returns a function, that function is already bound to john.
Here is a snippet of code from bindAll method.
Notice that bindAll internally calls bind and it overrides the existing attribute with the function returned by bind.
The other difference between bind and bindAll is that in bind first parameter is a function john.says and the second parameter is the value of this john. In bindAll first parameter is value of this john and the second parameter is not a function but the attribute name.
Things to watch out for
While developing a Backbone.js application someone had code like this
Above code will not work because the returned value of bind is not being used. The correct usage will be
Or you can use bindAll as given below.
C programming language allows developers to directly access the memory where variables are stored. Ruby does not allow that. There are times while working in Ruby when you need to access the underlying bits and bytes. Ruby provides two methods pack and unpack for that.
Here is an example.
In the above case ‘A’ is a string which is being stored and using unpack I am trying to read the bit value. The ASCII table says that ASCII value of ‘A’ is 65 and the binary representation of 65 is 10000010 .
Here is another example.
Notice the difference in result from the first case. What’s the difference between b* and B*. In order to understand the difference first lets discuss MSB and LSB.
Most significant bit vs Least significant bit
All bits are not created equal. C has ascii value of 67. The binary value of 67 is 1000011.
First let’s discuss MSB (most significant bit) style . If you are following MSB style then going from left to right (and you always go from left to right) then the most significant bit will come first. Because the most significant bit comes first we can pad an additional zero to the left to make the number of bits eight. After adding an additional zero to the left the binary value looks like 01000011.
If we want to convert this value in the LSB (Least Significant Bit) style then we need to store the least significant bit first going from left to right. Given below is how the bits will be moved if we are converting from MSB to LSB. Note that in the below case position 1 is being referred to the leftmost bit.
After the exercise is over the value will look like 11000010.
We did this exercise manually to understand the difference between most significant bit and least significant bit. However unpack method can directly give the result in both MSB and LSB. The unpack method can take both b* and B* as the input. As per the ruby documentation here is the difference.
Now let’s take a look at two examples.
Both b* and B* are looking at the same underlying data. It’s just that they represent the data differently.
Different ways of getting the same data
Let’s say that I want binary value for string hello . Based on the discussion in the last section that should be easy now.
The same information can also be derived as
Let’s break down the previous statement in small steps.
Directive C* gives the 8-bit unsigned integer value of the character. Note that ascii value of h is 104, ascii value of e is 101 and so on.
Using the technique discussed above I can find hex value of the string.
Hex value can also be achieved directly.
High nibble first vs Low nibble first
Notice the difference in the below two cases.
As per ruby documentation for unpack
A byte consists of 8 bits. A nibble consists of 4 bits. So a byte has two nibbles. The ascii value of ‘h’ is 104. Hex value of 104 is 68. This 68 is stored in two nibbles. First nibble, meaning 4 bits, contain the value 6 and the second nibble contains the value 8. In general we deal with high nibble first and going from left to right we pick the value 6 and then 8.
However if you are dealing with low nibble first then low nibble value 8 will take the first slot and then 6 will come. Hence the result in “low nibble first” mode will be 86.
This pattern is repeated for each byte. And because of that a hex value of 68 65 6c 6c 6f looks like 86 56 c6 c6 f6 in low nibble first format.
Mix and match directives
In all the previous examples I used *. And a * means to keep going as long as it has to keep going. Lets see a few examples.
A single C will get a single byte.
You can add more Cs if you like.
Rather than repeating all those directives, I can put a number to denote how many times you want previous directive to be repeated.
I can use * to capture al the remaining bytes.
Below is an example where MSB and LSB are being mixed.
pack is reverse of unpack
Method pack is used to read the stored data. Let’s discuss a few examples.
In the above case the binary value is being interpreted as 8 bit unsigned integer and the result is ‘A’.
In the above case the input ‘A’ is not ASCII ‘A’ but the hex ‘A’. Why is it hex ‘A’. It is hex ‘A’ because the directive ‘H’ is telling pack to treat input value as hex value. Since ‘H’ is high nibble first and since the input has only one nibble then that means the second nibble is zero. So the input changes from ['A'] to ['A0'] .
Since hex value A0 does not translate into anything in the ASCII table the final output is left as it and hence the result is \xA0. The leading \x indicates that the value is hex value.
Notice the in hex notation A is same as a. So in the above example I can replace A with a and the result should not change. Let’s try that.
Let’s discuss another example.
In the above example notice the change. I changed directive from H to h. Since h means low nibble first and since the input has only one nibble the value of low nibble becomes zero and the input value is treated as high nibble value. That means value changes from ['a'] to ['0a']. And the output will be \x0A. If you look at ASCII table then hex value A is ASCII value 10 which is NL line feed, new line. Hence we see \n as the output because it represents “new line feed”.
Usage of unpack in Rails source code
I did a quick grep in Rails source code and found following usage of unpack.
Already we have seen the usage of directive C* and H for unpack. The directive m gives the base64 encoded value and the directive U* gives the UTF-8 character. Here is an example.
Above code was tested with ruby 1.9.2 .
French version of this article is available here .
If you want output in xml format then request with .xml extension at the end like this localhost:3000/users.xml and you will get the output in xml format.
What we saw is only one part of the puzzle. The other side of the equation is HTTP header field Accept defined in HTTP RFC.
HTTP Header Field Accept
When browser sends a request then it also sends the information about what kind of resources the browser is capable of handling. Here are some of the examples of the Accept header a browser can send.
If you are reading this blog on a browser then you can find out what kind of Accept header your browser is sending by visiting this link. Here is list of Accept header sent by different browsers on my machine.
Let’s take a look at the Accept header sent by Safari.
Safari is saying that I can handle documents which are xml (application/xml), html (text/html) or plain text (text/plain) documents. And I can handle images such as image/png. If all else fails then send me whatever you can and I will try to render that document to the best of my ability.
Notice that there are also q values. That signifies the priority order. This is what HTTP spec has to say about q.
Each media-range MAY be followed by one or more accept-params, beginning with the “q” parameter for indicating a relative quality factor. The first “q” parameter (if any) separates the media-range parameter(s) from the accept-params. Quality factors allow the user or user agent to indicate the relative degree of preference for that media-range, using the qvalue scale from 0 to 1 (section 3.9). The default value is q=1.
The spec is saying is that each document type has a default value of q as 1. When q value is specified then take that value into account. For all documents that have same q value give high priority to the one that came first in the list. Based on that this should be the order in which documents should be sent to safari browser.
Notice that Safari is nice enough to put a lower priority for */*. Chrome and Firefox also puts */* at a lower priority which is a good thing. Not so with IE which does not declare any q value for */* .
Look at the order again and you can see that application/xml has higher priority over text/html. What it means is that safari is telling Rails that I would prefer application/xml over text/html. Send me text/html only if you cannot send application/xml.
And let’s say that you have developed a RESTful app which is capable of sending output in both html and xml formats.
Rails being a good HTTP citizen should follow the HTTP_ACCEPT protocol and should send an xml document in this case. Again all you did was visit a website and safari is telling rails that send me xml document over html document. Clearly HTTP_ACCEPT values being sent by Safari is broken.
HTTP_ACCEPT is broken
HTTP_ACCEPT attribute concept is neat. It defines the order and the priority. However the implementation is broken by all the browser vendors. Given the case that browsers do not send proper HTTP_ACCEPT what can rails do. One solution is to ignore it completely. If you want xml output then request http://localhost:3000/users.xml . Solely relying on formats make life easy and less buggy. This is what Rails did for a long time.
Starting this commit ,by default, rails did ignore HTTP_ACCEPT attribute. Same is true for Twitter API where HTTP_ACCEPT attribute is ignored and twitter solely relies on format to find out what kind of document should be returned.
Unfortunately this solution has its own sets of problems. Web has been there for a long time and there are a lot of applications who expect the response type to be RSS feed if they are sending application/rss+xml in their HTTP_ACCEPT attribute. It is not nice to take a hard stand and ask all of them to request with extension .rss .
Parsing HTTP_ACCEPT attribute
Parsing and obeying HTTP_ACCEPT attribute is filled with many edge cases. First let’s look at the code that decides what to parse and how to handle the data.
Notice that if a format is passed like http://localhost:3000/users.xml or http://localhost:3000/users.js then Rails does not even parse the HTTP_ACCEPT values. Also note that if browser is sending */* along with other values then Rails totally bails out and just returns Mime::HTML unless the request is ajax request.
Next I am going to discuss some of the cases in greater detail which should bring more clarity around this issue.
Case 1: HTTP_ACCEPT is */*
I have following code.
I am assuming that HTTP_ACCEPT value is */* . In this case browser is saying that send me whatever you got. Since browser is not dictating the order in which documents should be sent Rails will look at the order in which Mime types are declared in respond_to block and will pick the first one. Here is the corresponding code
What it’s saying is that if Mime::ALL is sent then pick the first one declared in the respond_to block. So be careful with order in which formats are declared inside the respond_to block.
The order in which formats are declared can be real issue. Checkout these twocases where the author ran into issue because of the order in which formats are declared.
So far so good. However what if there is no respond_to block. If I don’t have respond_to block and if I have index.html.erb, index.js.erb and index.xml.builder files in my view directory then which one will be picked up. In this case Rails will go over all the registered formats in the order in which they are declared and will try to find a match . So in this case it matters in what order Mime types are registered. Here is the code that registers Mime types.
Case 2: HTTP_ACCEPT with no */*
I am going to assume that in this case HTTP_ACCEPT sent by browser looks really simple like this
I am also assuming that my respond_to block looks like this
So browser is saying that I prefer documents in following order
The order in which formats are declared is
In this case rails will go through each Mime type that browser supports from top to bottom one by one. If a match is found then response is sent otherwise rails tries find match for next Mime type. First in the list of Mime types supported by browser is js and Rails does find that my respond_to block supports .js . Rails executes format.js block and response is sent to browser.
Case 3: Ajax requests
When an AJAX request is made the Safari, Firefox and Chrome send only one item in HTTP_ACCEPT and that is */*. So if you are making an AJAX request then HTTP_ACCEPT for these three browsers will look like
and if your respond_to block looks like this
then the first one will be served based on the formats order. And in this case html response would be sent for an AJAX request. This is not what you want.
This is the reason why if you are using jQuery and if you are sending AJAX request then you should add something like this in your application.js file
If you are using a newer version of rails.js then you don’t need to add above code since it is already take care of for you through this commit .
Trying it out
If you want to play with HTTP_ACCEPT header then put the following line in your controller to inspect the HTTP_ACCEPT attribute.
I used following rake task to set custom HTTP_ACCEPT attribute.
I got familiar with intricacies of mime parsing while working on
ticket #6022 .
A big thanks to
for patiently dealing with me while working on this ticket.
He likes to declare the variable where they are used to be sure that the variable being used is declared with var otherwise that variable will become global variable. This fear of accidentally creating a global variables wants him to see variable declaration next to where it is being used.
Use the right tool
In the above case user has declared payment variable in the middle so that he is sure that payment is declared. However if there is a typo as given below then he has accidentally created a global variable “payment”.
You can configure such that JSLint validation runs when you check your code into git or when you push to github. Or you can have a custom rake task. Many solutions are available choose the one that fits you. But do not rely on manual inspection.
Variable declaration are being moved to the top by the browser
Take a look at following code. One might expect that console.log will print “Neeraj” but the output will be “undefined” . That is because even though you have declaration variables next to where they are being used, browsers lift those declarations to the very top.
Browser converts above code into one shown below.
In order to avoid this kind of mistakes it is preferred to declared variables at the top like this.
Looking at the first set of code a person might think that
Implications on how functions are declared
There are two ways of declaring a function.
In the first case only the variable declaration myfunc is getting hoisted up. The definition of myfunc is NOT getting hoisted. In the second case both variable declaration and function definition is getting hoisted up. For more information on this refer to my previous blog on the same topic.
jQuery 1.4.3 was recently released. If you upgrade to jQuery 1.4.3 you will notice that the behavior of return false has changed in this version. First let’s see what return false does.
First ensure that above code is executed on domready. Now if I click on any link then two things will happen.
As the name suggests, calling e.preventDefault() will make sure that the default behavior is not executed.
If above link is clicked then the default behavior of the browser is to take you to www.google.com. However by invoking e.preventDefault() browser will not go ahead with default behavior and I will not be taken to www.google.com.
When a link is clicked then an event “click event” is created. And this event bubbles all the way up to the top. By invoking e.stopPropagation I am asking browser to not to propagate the event. In other words the event will stop bubbling.
If I click on “click me” then “click event” will start bubbling. Now let’s say that I catch this event at .two and if I call e.stopPropagation() then this event will never reach to .first .
First note that you can bind more than one event to an element. Take a look at following case.
I am going to bind three events to the above element.
In this case there are three events bound to the same element. Notice that second event binding invokes e.stopImmediatePropagation() . Calling e.stopImmediatePropagation does two things.
Just like stopPropagation it will stop the bubbling of the event. So any parent of this element will not get this event.
However stopImmdiatePropagation stops the event bubbling even to the siblings. It kills the event right then and there. That’s it. End of the event.
Once again calling stopPropagation means stop this event going to parent. And calling stopImmediatePropagation means stop passing this event to other event handlers bound to itself.
Now that I have described what preventDefault, stopPropagation and stopImmediatePropagation does lets see what changed in jQuery 1.4.3.
In jQuery 1.4.2 when I execute “return false” then that action was same as executing:
Now e.stopImmediatePropagation internally calls e.stopPragation but I have added here for visual clarity.
Fact that return false was calling e.stopImmeidatePropagation was a bug. Get that. It was a bug which got fixed in jquery 1.4.3.
So in jquery 1.4.3 e.stopImmediatePropagation is not called. Checkout this piece of code from events.js of jquery code base.
As you can see when return false is invoked then e.stopImmediatePropagation is not called.
I tried to find which commit made this change but I could not go far because of this issue.
It gets complicated with live and a bug in jQuery 1.4.3
To make the case complicated, jQuery 1.4.3 has a bug in which e.preventStopImmediatePropagation doest not work. Here is a link to this bug I reported.
To understand the bug take a look at following code:
Since I am invoking e.stopImmediatePropagation I should never see alert world. However you will see that alert if you are using jQuery 1.4.3. You can play with it here .
This bug has been fixed as per this commit . Note that the commit mentioned was done after the release of jQuery 1.4.3. To get the fix you will have to wait for jQuery 1.4.4 release or use jQuery edge.
I am using rails.js (jquery-ujs). What do I do?
As I have shown “return false” does not work in jQuery 1.4.3 . However I would have to like have as much backward compatibility in jquery-ujs as much possible so that the same code base works with jQuery 1.4 through 1.4.3 since not every one upgrades immediately.
should make jquery-ujs jquery 1.4.3 compatible.
have been logged at jquery-ujs and I will take a look at all of them one by one. Pleaes do provide your feedback.
Nothing great there. However try passing a parameter to instance_eval .
You will get following error.
So instance_eval does not allow you to pass parameters to a block.
How to get around to the restriction that instance_eval does not accept parameters
instance_exec was added to ruby 1.9 and it allows you to pass parameters to a proc. This feature has been backported to ruby 1.8.7 so we don’t really need ruby 1.9 to test this feature. Try this.
Above code works. So now we can pass parameters to block. Good.
Changing value of self
Another feature of instance_exec is that it changes the value of self. To illustrate that I need to give a longer example.
Notice that in that above case Developer.lab says “Human”. And that is the right answer from ruby perspective. However that is not what I intended. ruby stores the binding of the proc in the context it was created and hence it rightly reports that self is “Human” even though it is being called by Developer.
Rails developers know that in development mode classes are loaded on demand. In production mode all the classes are loaded as part of bootstrapping the system. Also in development mode classes are reloaded every single time page is refreshed.
In order to reload the class, Rails first has to unload . That unloading is done something like this.
However a class might have other constants and they need to be unloaded too. Before you unload those constants you need to know all the constants that are defined in the class that is being loaded. Long story short rails keep track of every single constant that is loaded when it loads User or UserController.
Dependency mechanism is not perfect
Sometimes dependency mechanism by rails lets a few things fall through the crack. Try following case.
Start the server in development mode and visit http://localhost:3000/users . First time every thing will come up fine. Now refresh the page. This time you should get an exception uninitialized constant OpenURI .
So what’s going on.
After the page is served the very first time then at the end of response rails will unload all the constants that were autoloaded including UsersController. However while unloading UsersContorller rails will also unload OpenURI.
When the page is refreshed then UsersController will be loaded and require 'open-uri' will be called. However that require will return false.
Why require returns false
Try the following test case in irb.
step 3 : ensure that OpenStruct is truly removed
Notice that in the above case in step 4 require returns false. ‘require’ checks against $LOADED_FEATURES. When OpenStruct was removed then it was not removed from $LOADED_FEATURES and hence ruby thought ostruct is already loaded.
How to get around to this issue.
require loads only once. However load loads every single time. In stead of ‘require’, ‘load’ could be used in this case.
Back to the original problem
In our rails application refresh of the page is failing. To get around to that issue use require_dependency instead of require. require_dependency is a rails thing. Under the hood rails does the same trick we did in the previous step. Rails calls kernel.load to load the constants that would fail if require were used.
Every one knows for sure that hoptoad notifier sends exception messages to server in production environment. Between ‘development’ and ‘production’ there could be a number of environments. Some of these would have settings closer to ‘development’ environment and some would have setting closely matching the settings of ‘production’ environment.
When you have many environments and when an exception occurs, one is not really sure if that message is getting logged at hoptoad or not. Here is a run down of which messages will get logged and why.
It alls starts with rails
When an exception occurs while rendering a page then action_controller catches the exception. Following logic is evaluated to decide if user should see an error page with full stack trace or ‘we are sorry something went wrong’ message.
Let’s look at first part consider_all_requests_local . Open ~/config/environments/development.rb and ~/config/environments/production.rb .
As you can see in development mode all requests are local. Be careful with what you put in your intermediary environments.
If you want to override that value then you can do like this.
The second part of the equation was local_request? .
Rails has following code for that method.
As you can see all requests coming from 127.0.0.1 are considered local even if RAILS_ENV is ‘production’. For testing purpose you can override this value like this.
Hoptoad has access to exception now what
If consider_all_request_local is false and if request is not local then hoptoad will get access to exception thanks to alias_method_chain.
In rescue_action_in_public_with_hoptoad there is a call to notify_or_ignore like this.
For majority of us there is no special handling for a particular user_agent .
Hoptoad defines following methods as ignorable by default and you won’t get notifications for following types of exceptions.
Next hop is method send_notice .
configuration.public? is defined like this.
As you can see if the Rails.env is development or test or cucumber the exception will not be reported to hoptoad server.
Defining regular expressions
If I am defining regular expression using RegExp then I need to add escape character in certain cases.
When I am defining regular expression using RegExp then \w needs to be escaped otherwise it would be
test method is to check if a match is found or not. This method returns true or false.
exec method finds if a match is found or not. It returns an array if a match is found. Otherwise it returns null.
match method acts exactly like exec method if no g parameter is passed. When global flag is turned on the match returns an Array containing all the matches.
Note that in exec the syntax was regex.exec(text) while in match method the syntax is
Now with global flag turned on.
Getting multiple matches
Once again both exec and match method without g option do not get all the matching values from a string. If you want all the matching values then you need to iterate through the text. Here is an example.
Get both the bug numbers in the following case.
Note that in the above case global flag g. Without that above code will run forever.
In the above case match is used instead of regex . However since match with global flag option brings all the matches there was no need to iterate in a loop.
When a match is made then an array is returned. That array has two methods.
index: This tells where in the string match was done
The requirement given to me states that I should strictly look for word
java, ruby or rails within word boundary. This can be done like this.
Above code works. However notice the code duplication. This can be refactored to the one given below.
Above code works and there is no code duplication. However in this case I am asking regular expression engine to create a captured group which I’ll not be using. Regex engines need to do extra work to keep track of captured groups. It would be nice if I could say to regex engine do not capture this into a group because I will not be
?: is a special symbol that tells regex engine to create non capturing group. Above code can be refactored into the one given below.
This was question #5 in the original blog. I have modified the quiz a little bit to suit my needs.
In the above case output is undefined. This is because this refers to a property named x and since no such property was found undefined is the answer.
Above code causes ReferenceError because x is not defined. Same thoery applies here. In this case x is a variable and since no such variable was found code failed.
Coming back to the third part of the original question. This one uses call.
Alex Sexton wrote a wonderful article on how to use inheritance pattern to manage large piece of code. His code also has a practical need for prototypal inheritance for writing modular code.
Creating standard jQuery plugin
Given below is code that does exactly what Alex’s code does.
For smaller plugins this code is not too bad. However if the plugin is huge then it presents one big problem. The code for business problem and the code that deals with jQuery is all mixed in. What it means is that if tomorrow same functionality needs to be implemented for Prototype framework then it is not clear what part of code deals with framework and what part deals with business logic.
Separating business logic and framework code
Given below is code that separates business logic and framework code.
This code is an improvement over first iteration. However the whole business logic is captured inside a function. This code can be further improved by embracing object literal style of coding.
Third and final iteration of the code is the code presented by Alex.
Notice the Object.create pattern Alex used.
However the problem is that you can’t create a new on that object.
And you need to create new object so that you could dole out new objects to each element.
Object.create pattern comes to rescue.
This pattern takes a standard Object and returns an instance of a function.
This function has the input object set as prototype.
So you get a brand new object for each element and you get to have all your business logic in object literal way and not in a function.
If you want to know more about prototypal inheritance then you can read more about it in previous blog .
In the beginning there was duplication
As you can see both Person and Developer objects have votingAge property. This is code duplication. This is an ideal case where inheritance can be used.
Refactoring code to make use of prototype method
Currently Person function is defined like this.
Problem with above code is that every time a new instance of Person is created, two new properties are created and they take up memory. If a million objects are created then all instances will have a property called votingAge even though the value of votingAge is going to be same. All the million person instances can refer to same votingAge method if that method is define in prototype. This will save a lot of memory.
Bringing inheritance using prototype property
Currently Person is defined like this.
If Developer Object wants to extend Person then all that needs to be done is this.
Now Developer instance will have access to votingAge method. This is much better. Now there is no code duplication between Developer and Person.
However notice that looking for votingAge method from a Developer instance will take an extra hop.
Next engine will look for votingAge property in its prototype property of Developer instance which is an instance of Person. votingAge method is not declared in the Person instance.
Next engine will look for votingAge property in the prototype of Person instance and this method would be found.
Since only the methods that are common to both Developer and Person are present in the Person.prototype there is nothing to be gained by looking for methods in the Person instance. Next implementation will be removing the middle man.
Remove the middle man
Here is the revised implementation of Developer function.
In the above case Developer.prototype directly refers to Person.prototype. This will reduce the number of hops needed to get to method votingAge by one compared to previous case.
However there is a problem. If Developer changes the common property then instances of person will see the change. Here is an example.
In order to solve this problem Developer.prototype should point to an empty object. And that empty object should refer to Person.prototype .
Solving the problem by adding an empty object
Here is revised implementation for Developer object.
Let’s test this code.
As you can see with the introduction of empty object, Developer instance have votingAge of 18 while Person intances have votingAge of 21.
If child wants to access super object then that should be allowed. That can be accomplished like this.
Capturing it as a pattern
The whole thing can be captured in a helper method that would make it simple to create inheritance.
Pure prototypal inheritance
A simpler form of pure prototypal inheritance can be structured like this.
You can see that Object.create takes only one parameter. This method does not necessarily create a parent child relationship . But it can be a very good tool in converting an object literal to a function.
Checkout following jQuery code written with jQuery.1.4.2. What do you think will happen when first link is clicked.
I was expecting that I would see both the messages. However jQuery only invokes the very first message.
return false does two things. It stops the default behavior which is go and fetch the link mentioned in the
href of the anchor tags. Also it stops the event from bubbling up. Since live method relies on event bubbling, it makes sense that second message does not appear.
Fix is simple. Just block the default action but let the event bubble up.