Page 1 of 1
How do you guys extend your classes in JS
Posted: Tue Jan 21, 2014 9:42 pm
by Chris
I always see people using some fancy extend function and I always ask myself why.. Is this not supported in every browser?
Code: Select all
lol = function(){ this.haha = 'lol' }
haha = function(){ lol.call(this) }
new haha()
result:
Re: How do you guys extend your classes in JS
Posted: Tue Jan 21, 2014 10:00 pm
by hallsofvallhalla
what version of Internet Craporer is it supported up to?
Re: How do you guys extend your classes in JS
Posted: Tue Jan 21, 2014 10:26 pm
by Chris
From what I can tell at leats IE 6
Alerts lol:
Code: Select all
javascript: lol = function(){ this.haha = 'lol'; }; haha = function(){ lol.call(this); }; alert(new haha().haha); void 0;
Re: How do you guys extend your classes in JS
Posted: Tue Jan 21, 2014 11:08 pm
by hallsofvallhalla
interesting.....
Re: How do you guys extend your classes in JS
Posted: Tue Jan 21, 2014 11:26 pm
by Jackolantern
If I am using jQuery (and I usually have it loaded through a popular CDN), I will typically use jQuery's
extend function. If I don't have it loaded, or I am in node or something else, it isn't that hard to just recreate it.
While it is a bit off-topic, I thought I would mention something pretty cool I stumbled across the other day. Support for it is still spreading, and obviously won't work in ancient versions of IE, but
Object.create() is a very cool function. One of the issues with working extensively with JS object literals is that they lend themselves much better to being one-off objects, rather than something to be instantiated with independent data. This is one of the reasons I have heard people cite as to why they use object constructor functions rather than literals (and although it is a taste thing, I believe object literals are simply more powerful than constructor methods and using "new"). But Object.create() allows you to create more of the same object, with independent data. It is almost like having a "new" keyword for object literals!

Re: How do you guys extend your classes in JS
Posted: Wed Jan 29, 2014 7:24 am
by fang
The problem with this method is that the parent's prototype chain is lost.
Code: Select all
>>> function objparent() { this.what = 'lol' }
undefined
>>> objparent.prototype.WHAT = function() { console.log('what') }
function()
>>> function myobj() { objparent.call(this) }
undefined
>>> myobj.prototype.something = 'abc'
"abc"
>>> x = new myobj()
x { what="lol", something="abc"}
>>> x.WHAT()
TypeError: what.WHAT is not a function
I'd recommend also adding, just before the child object prototype properties are added, something along the lines of
This might not work in legacy browsers though; anyone know offhand?