Thursday, August 5, 2010

Constructors without using "new"

When creating a constructor in Javascript, one has to worry about a problem: what if someone calls your constructor without using new?

function Point(x,y) {
  this.x = x;
  this.y = y
}

// This is good
var pt = new Point(20,30);

// This is not
var pt2 = Point(20,30);

You'll notice when you don't use new, pt2 is undefined after the call. Even worse, we've added two variables to the global scope, x, y. That is because if you call a function without specifying the context, the browser passes in the global object, which is "window";

The first attempt to fix this is the following

function Point(x,y) {
  if (this instanceof Point) {
    this.x = x;
    this.y = y
  } else {
    return new Point(x,y);
  }
}

// This is good
var pt = new Point(20,30);

// This is OK also
var pt2 = Point(20,30);

However, that seems like a lot of boiler plate code to add to every constructor. How can we abstract that? Here's what I came up with.

/**
 * Wraps the passed in constructor so it works with
 * or without the new keyword
 * @param {Function} realCtor The constructor function.
 *    Note that this is going to be wrapped
 *    and should not be used directly 
 */
function ctor(realCtor){
  // This is going to be the actual constructor
  return function wrapperCtor(){
    var obj; // object that will be created
    if (this instanceof wrapperCtor) {
      // Called with new
      obj = this;
    } else {
      // Called without new. Create an empty object of the
      // correct type without running that constructor
      surrogateCtor.prototype = wrapperCtor.prototype;
      obj = new surrogateCtor();
    }
    // Call the real constructor function
    realCtor.apply(obj, arguments);
    return obj;
  }
}

/** 
 * A function that does nothing, so we can create objects 
 * of a prototype without running unnecessary code. 
 * See its usage above
 */
function surrogateCtor() {}

// Create our point contructor
Point = ctor(function(x,y){
  this.x = x;
  this.y = y;
});

// This is good
var pt = new Point(20,30);
// This is OK also
var pt2 = Point(20,30);

// It's even ok with inheritance, though a 3D point shouldn't
// really inherit from a 2D point, it's just to make a point...
Point3D = ctor(function(x,y,z){
  Point.call(this, x, y);  
  this.z = z;
});

// Note that this is not the best way to setup inheritance.
// My next post will explain a better way
Point3D.prototype = new Point();

var pt3D = new Point3D(5,3,8);

// Outputs true
console.log(pt3D instanceof Point3D && pt3D instanceof Point);

75 comments:

  1. Hey man, good blog btw.
    I kinda have mix feelings about this no "new" keyword for class instantiation.
    I think the new keyword explicitly say that this is your brand new instance of this object and nothing else.
    Now with no new keyword it seems like it is not a new instance of this class, and worse yet, it could confuse with the Singletons that you might want to create shorthand, ie: dh = Ext.Domhelper;
    I understand the problems that occur when someone instantiate your class with no new keyword, but then again, they shouldn't be doing that anyway.
    I never seen in any tutorial someone saying that you could use either way (new/no new); google just released their new google map v3 and if you dont say "new google.maps.Map(map-id, mapoptions)" you wont get anything back.
    That is just what I think, you dont have to agree with me though :)

    ReplyDelete
  2. @bostonian: To be honest, I don't really use this in my code, so I do agree with you. This post is more about explaining how to do it if you wanted to. Say, someone writing a library trying to make it more fool proof.

    ReplyDelete
  3. So you think that is more intuitive to someone reading your code than adding

    if (!(this instanceof Point))
    return new Point(x, y);

    to the top of your constructors? :)

    ReplyDelete
  4. @Jaka: Great point. Had I thought of reversing my if/else when writing the post, I probably would have stopped at that since that doesn't feel like too much boiler plate code. Still, abstracting the idea allows it to be used transparently from a library that helps with JS inheritance like http://edspencer.net/2011/01/classes-in-ext-js-4-under-the-hood.html or http://mootools.net/docs/core/Class/Class

    ReplyDelete
  5. Cool tips. Too bad you haven't had time to keep posting...

    ReplyDelete
  6. Your blog is so beautiful, interesting and inspiring! I just found you through an article about meaning. I can't wait to take your courses!
    Romwe Track order,
    Romwe Customer Service

    ReplyDelete
  7. You can follow the instructions below to install the setup on your devices such as Windows PC, Mac, or mobile device. www.eset.com/ca/download Best IT security solutions for your home and business devices. Try ESET antivirus and internet security solutions for Windows, Android, Mac or Linux OS.www.eset.com/us/activate

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. At Infotrench SEO Company - Innovation, quality, creativity, and promptness are the main mantras of Infotrench Technologies and we imbibe these mantras in our work, to the core.
    Digital Marketing Company in Bhopal
    Search Engine Optimization Company in Bhopal

    ReplyDelete
  10. Nice article thanks for sharing this informative post keep it up.
    How to track a phone
    IMEI tracking

    ReplyDelete
  11. Hi, myself Audrey Cruz, a professional Chemistry tutor as well as writer who works with EssayCorp. I like to share different topics and tips to students so that they can get done with their Chemistry projects and assignments.

    Visit Chemistry Assignment Help Book Now And Get 10% Off on Chemistry Assignment

    ReplyDelete
  12. Supplier4buyer.com is India's largest online marketplace that assists manufacturers, suppliers & exporters to trade with each other at a common, reliable & transparent platform. Get here quality products, trade leads, manufacturers, suppliers, exporters & international buyers.
    Stainless Steel Alloys | Stainless Steel Gate | Steel Pipes and Tubes | steel ruler

    ReplyDelete
  13. Your blog is very creative and uefull…rokucomlink1.sitey.me is the free official site to link, activate, set-up and manage your Roku player or Roku TV. Roku never charges for linking or set-up support.
    roku activation link

    ReplyDelete
  14. Make sure your console is connected to the Internet microsoft.com/redeem and you’re signed in to the Microsoft account on which you want to Microsoft redeem code. Press the Guide button on the controller. Choose Games and apps Redeem code. Enter the gift card code and select Done. This is very simple to redeem microsoft redeem code or microsoft.com/redeem.

    ReplyDelete
  15. The hp support is actually a website which is set up by HP technicians to help people set up their HP Printer by downloading the printer drivers and other software through this website.
    hp.com/support ,
    www.hp.com/support ,
    123.hp.com/setup

    ReplyDelete
  16. canon.com/ijsetup offers the Printer Setup download link where you can install the printer setup further. office.com/setup gives multiple options to activate and register setup for everything you work on office products. Visit roku.com/link and enter the link code shown on your display to connect Roku with your account and device as well.

    ReplyDelete
  17. Twitch TV has been the greatest and the most famous video streaming platform for every gamer on this planet.
    twitch.tv/activate
    The hp.com/123 is actually a website which is set up by HP technicians to help people set up their HP Printer. Go to mcafee. com/activeate and register your subscribed McAfee product such as McAfee total protection or McAfee Internet Security.

    ReplyDelete

  18. Download Trend Micro Antivirus through www.trendmicro.com besbuypc and then install it. Reach www.trendmicro.com/bestbuypc and proceed Trend micro download for any of device including PC, Mac, or mobile phones. The correct canon printer drivers device drivers must be installed for a Canon Inkjet Printer to function properly. Go to webroot.com/safe and download the Webroot. Using the Webroot antivirus program, you can protect your devices such as Windows, Mac and mobile devices from malware, virus, spyware, etc.

    ReplyDelete
  19. Very nice blog post, thankyou for sharing such information. i have also some links to share.

    Visit: www.norton.com/setup

    ReplyDelete
  20. Thank you for sharing such a great post, its very helpful.
    www.norton.com/setup

    ReplyDelete
  21. Webroot geek squad download antivirus protection system is an awe-inspiring protection system which offers the world class security. No matter, whether a person is surfing the internet for personal use or has a small to big-sized business.

    ReplyDelete
  22. I am really grateful to the holder of this web page who has shared this fantastic article at at this place.
    www.trendmicro.com/downloadme

    ReplyDelete
  23. www.webroot.com/safe
    is undoubtedly one of the most appreciated and renowned for removing viruses and restricting malicious links and sites to open on the device and thus it protects data and devices on a large scale.

    ReplyDelete
  24. www.norton.com/setup
    - Norton is unarguably one of the most popular and used antivirus programs. It stands on most of the expectations of consumers and office workers as it is cross-platform compatible on most of the devices and OS.

    ReplyDelete

  25. Webroot.com/safe to opt best security for your all digital devices. No one can deny the fact that Internet is our primary need today and devices connected with internet are always in high risk of virus attacks.
    Webroot.com/safe

    ReplyDelete
  26. Webroot geek squad download can be easily done from webroot.com/safe . currently days we tend to all area unit mistreatment device to finish our digital task i.e. Shopping, Education, Banking etc.
    Webroot geek squad download

    ReplyDelete
  27. This post is very useful to us thanks for sharing this info with us…
    www.webroot.com/safe

    ReplyDelete
  28. www.malwarebytes.com/install – Malware may affect your device if you click on a suspicious email attachment, although it is not limited to that. Malware also arises from unreliable sources via software facilities and when you visit infected websites.

    ReplyDelete
  29. comcast email sign in, you have many options for checking your email account, which is branded as Xfinity email. You can enter your Comcast inbox with a webmail service similar to other popular tools from Microsoft or Google.

    ReplyDelete

  30. We are well established IT and outsourcing firm working in the market since 2013. We are providing training to the people ,
    like- Web Design , Graphics Design , SEO, CPA Marketing & YouTube Marketing.Call us Now whatsapp: +(88) 01537587949
    :Email Marketing Service in bangladesh
    Free bangla sex video:careful
    good post outsourcing institute in bangladesh

    ReplyDelete


  31. aol desktop gold download – This is popular with all fresh user interface characteristics and features that are now accessible, and advance safety features. AOL Gold can assist you access your messages, search for content, and even browsing. Among all web interfaces, AOL Gold is best.

    ReplyDelete
  32. www.webroot.com/safe is one of the easiest processes to secure your online web surfing and data. If you want to secure your devices from virus and malware just download webroot with key code from webroot com safe website. Learn the steps to download, install, activate or reinstall webroot.

    ReplyDelete
  33. webroot.com/safe : we are best in our Industry, In one click Install wsainstall exe from webroot.com/safe for Windows device.

    ReplyDelete
  34. Get everything you need for you, friends & family - day & night, active & night wear, party supplies & gifts at the comfort of your home … in short … “Socho aur Lailoo”.
    You can also add your desire items by sending message in your wish list if you are unable to find in our store,Our professionals get it for you at the best rates. lsm fabrics

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Shreeja Health Care is leading manufacturer of Oil Maker Machine . Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed etc.

    ReplyDelete
  37. I was very impressed to see this post, the steps to activate using then it's good to read the latest articles and blog posts on our page.www.trendmicro.com/bestbuypc

    ReplyDelete
  38. Utilizing the provided controller, press the HOME or MENU button.
    Choose Video, Application, My Apps or Apps, contingent upon your model.
    Choose the Prime Video application.
    Choose Sign In and Start Watching and note the enlistment code that shows up on the system.
    Utilizing the web, go to the Amazon™ sign-in page

    amazon.com/mytv
    www.amazon.com/mytv enter code sign in
    www.amazon.com/mytv
    www.primevideo.com/mytv
    amazon prime login
    www.primevideo.com/mytv register code

    ReplyDelete

  39. The IJ Canon Pixma TS3322 all in one printer that allows the users to print, scan and copy the documents without any troubles
    ij.start canon |

    ReplyDelete
  40. Hey, I am James smith works as an “Printer Expert” in HP Printer.
    visit:123.hp.com/setup

    ReplyDelete
  41. Laxmi pipe Industries is leading ss pipe manufacturer . We are also manufactures and exporter of steel pipes & tubes.

    ReplyDelete
  42. I was very impressed to see this post, the steps to activate using then it's good to read the latest articles and blog posts on our page.
    www.trendmicro.com/bestbuypc

    ReplyDelete

  43. What a fantastic post! This is so chock full of useful information I can't wait to dig deep and start utilizing the resources you have given me. your exuberance is refreshing

    you've outdone yourself this time

    This is probably the best, most concise step-by-step guide I've ever seen on how to build a successful blog. i am also writing blog about the kindly review it french language institute in delhi .

    ReplyDelete
  44. Shreeja Health Care is leading manufacturer of Oil Maker Machine. Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed etc.

    ReplyDelete
  45. Canon.com/ijsetup is a site that gives you a protected, secure, and dependable stage for downloading the driver. ... After the driver arrangement is done, you can utilize the product for controlling and commanding your printer to print your attractive records.canon.com/ijsetup | ij.start.cannon

    ReplyDelete
  46. After this process, I execute the show to finish the setup process. I am confronting 123.hp.com/envy issues in this process, so I need to take the unique help from an online technician.

    ReplyDelete
  47. McAfee WebAdvisor is your trusty companion that helps keep you safe from threats while you browse and search the web.
    McAfee Webadvisor

    ReplyDelete
  48. Many email users are facing a common problem i.e. forgetting the password of their email account. If any Yahoo email user wants to know about Yahoo mail forgot password and security question. If you have any problem with your Yahoo account or you cannot head your Yahoo account after many attempts then you can go to Yahoo mail forgot password and security question

    How Yahoo mail forgot password and security question


    How Yahoo account recovery phone number

    How To Recover Yahoo Mail Account

    Cannot Login To Yahoo Mail


    Yahoo mail Login USal



    ReplyDelete
  49. I savour, lead to I found exactly what I used to be having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye 카지노사이트

    ReplyDelete
  50. I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future 토토사이트

    ReplyDelete
  51. Very nice blog with full of technology keep spreading and sharing your knowledge to other.Computers & Peripherals

    ReplyDelete

  52. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info.
    Feel free to visit my website; 야설

    ReplyDelete
  53. This really is an incredibly amazing powerful resource that you’re offering and you just provide it away cost-free!! I comparable to discovering websites that view the particular price of providing you beautiful learning resource for zero cost. We truly dearly loved examining this web site. Be thankful! Feel free to visit my website; 국산야동



    ReplyDelete

  54. Great blog here! Additionally your website quite a bit up very fast! What web host are you the use of? Can I am getting your affiliate hyperlink on your host? Feel free to visit my website; 일본야동

    ReplyDelete

  55. Admiring the time and energy you put into your site and in depth information you offer. Feel free to visit my website; 한국야동

    ReplyDelete
  56. As a professional New World Coins supplier, NewWorldCoins has been accompanying the growth of New World. They have been working hard to bring players the New World Coins with low price and high security. With its help, many players can experience this high-quality MMO more easily. Moreover, the transactions conducted in NewWorldCoins are absolutely convenient and fast, it provides players with the fastest delivery speed and the most reliable refund policy.In short, it is a 100% trusted seller, and you will never regret buying New World Coins here.

    ReplyDelete
  57. Thanks for Sharing with nice comment. Get your hands on the latest set-by-step guide for HP Deskjet 3755 wireless setup. All you need to do is to follow the steps in order to avoid issues.

    ReplyDelete
  58. Amazing article u will love it. https://bit.ly/3mUiKSN

    ReplyDelete
  59. Cricut com setup is a machine designed to cut your paper, cardboard, or any other material into specific shapes. The Cricut machine provides software for your device named Cricut Design space.

    Cricut.com/Setup
    cricut.com setup
    cricut.com/setup maker
    cricut.com/setup mug press

    ReplyDelete
  60. Sometimes, you might need to verify the credentials that have been submitted. This could be your email address, phone number or any other information that the website requires. These codes can be sent to you via email or text message along with your submitted information as you check out.amazon mytv
    amazon com mytv
    amazon code
    amazon mytv
    amazon code

    ReplyDelete
  61. After you have successfully signed in, you will receive a code on the Roku channel. Log in to Roku to receive a code.
    google play redeem code
    chilis gift card balance
    amex gift card balance
    kohl's gift card balance
    starbucks gift card balance

    ReplyDelete
  62. I am Sudhanshu and I will help you with website ranking you can contact me anytime and sure we will rank your website on search Engines.
    visit us .best digital marketing
    Call us:+91 9999992103

    ReplyDelete
  63. This comment has been removed by the author.

    ReplyDelete