Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Extends Object with custom method for instantiating objects.
- *
- * @param {Object} className Object to create from.
- * @param {Object|Function} params Params to the constructor method, or extended/custom constructor function.
- * @param {String} constructor Name of constructor function.
- * @returns {Object}
- */
- Object.init = function(className, params, constructor)
- {
- constructor = constructor || '_constructor';
- var Obj = Object.create(className) || {};
- if( typeof params === 'object' && typeof Obj[constructor] === 'function' )
- {
- Obj[constructor](params);
- }
- else if( typeof params === 'function' )
- {
- if( typeof Obj._constructor !== 'function' )
- {
- Obj._constructor = params;
- Obj._constructor();
- }
- else
- {
- var oldConstructor = Obj._constructor;
- Obj._constructor = function() {
- oldConstructor();
- params();
- }
- }
- }
- return Obj;
- }
- var PlaceholderRotator = {
- /**
- * Amount of time text is fully readable before deleting.
- * @type Number
- */
- defaultShowTime : 2000,
- /**
- * Amount of time between typing a character.
- * @type Number
- */
- timeBetweenCharacterType : 10,
- /**
- * Amount of time between deleting a character.
- * @type Number
- */
- timeBetweenCharacterDeletion : 5,
- /**
- * Constructor function.
- * @param {Object} params
- * @returns {undefined}
- */
- _constructor: function(params)
- {
- this.defaultShowTime = params.defaultShowTime || this.defaultShowTime;
- this.timeBetweenCharacterType = params.timeBetweenCharacterType || this.timeBetweenCharacterType;
- this.timeBetweenCharacterDeletion = params.timeBetweenCharacterDeletion || this.timeBetweenCharacterDeletion;
- }
- };
- // Example usages
- var a = Object.init(PlaceholderRotator, {
- defaultShowTime : 1000,
- timeBetweenCharacterType : 5
- });
- var b = Object.init(PlaceholderRotator, function() {
- console.log('This is an extended/custom constructor method.');
- });
- b.extendedFunction = function()
- {
- console.log('This is an extended function exclusively for b.');
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement