Created
September 16, 2012 18:32
-
-
Save smithcommajoseph/3733642 to your computer and use it in GitHub Desktop.
js extends vs extend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//A rough demo of extends vs extend | |
/* | |
* Extends - the second object needs to already be initialized | |
* after that, it will extend the first object | |
* | |
* var o1 = {"a": 1, "b": 2}; | |
* var o2 = {}; | |
* o2.extends(o1); | |
*/ | |
Object.prototype.extends = function(ext){ | |
var self = this; | |
for(var n in ext){ | |
if(ext.hasOwnProperty(n) && !self.hasOwnProperty(n)){ | |
self[n] = ext[n]; | |
} | |
} | |
return self; | |
} | |
/* | |
* Extend - the second object DOES NOT need to be initialized | |
* in order to extend the first object | |
* | |
* var o1 = {"a": 1, "b": 2}; | |
* var o2 = o1.extend({}) | |
* OR overrided the orig vals | |
* var o2 = o1.extend({a: moo}) | |
*/ | |
Object.prototype.extend = function(ext){ | |
var self = this; | |
// can add this line as a safty net. adds some parity to | |
// the above 'extends' example | |
ext = (typeof ext === "undefined") ? {} : ext | |
for(var n in self){ | |
if(self.hasOwnProperty(n) && !ext.hasOwnProperty(n)){ | |
ext[n] = self[n]; | |
} | |
} | |
return ext; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment