Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created December 13, 2013 07:55
Show Gist options
  • Select an option

  • Save CatTail/7941112 to your computer and use it in GitHub Desktop.

Select an option

Save CatTail/7941112 to your computer and use it in GitHub Desktop.
Use a function to mock new operator
/**
* Mock new operator.
* Worked just as new operator.
* @param {Function} Type
* @param {...*} opt_args
* @return {*}
*/
var newFunc = function(Type, opt_args) {
var Ctor, proto;
Ctor = function(){};
Ctor.prototype = Type.prototype;
proto = new Ctor();
return Type.apply(proto, Array.prototype.slice.call(arguments, 1)) || proto;
};
describe('newFunc', function() {
it('should act as new operator', function() {
var Ctor = function(value){ this.key = value; };
var value = 'test-value';
var obj = qd.newFunc(Ctor, value);
expect(obj instanceof Ctor).toEqual(true);
expect(obj.key).toEqual(value);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment