Skip to content

Instantly share code, notes, and snippets.

@davidjbeveridge
Created August 12, 2014 18:18
Show Gist options
  • Save davidjbeveridge/3cb4fbb5e367a6fdeca4 to your computer and use it in GitHub Desktop.
Save davidjbeveridge/3cb4fbb5e367a6fdeca4 to your computer and use it in GitHub Desktop.
Homework #1: create instances without the `new` operator
/** Write a function that will emulate the behavior of the `new` operator. I
* should be able to pass it a constructor function and some arguments, and get
* back an instance of it. Here's a test case; just fill in the
* `createInstance` function.
*
* You can just run the code to see if it works; if it doesn't work, assert will
* throw errors.
*
* To run it, just use `node create_instance.js`
*/
function createInstance() {
// Fill in here...
}
// constructor function for our test case
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHi = function() {
return 'Hi, my name is '+this.name+'.';
};
// Some assertion functions we can play with
function assert(condition, message) {
if(!condition) {
throw new Error(message);
}
}
function assert_equal(obj1, obj2) {
assert(obj1 === obj2, 'Expected '+obj1+' to equal '+obj2+'.');
}
// The actual test case:
var david = createInstance(Person, 'David', 28);
assert_equal(david.constructor, Person);
assert_equal(david.name, 'David');
assert_equal(david.age, 28);
assert_equal(david.sayHi(), 'Hi, my name is David.');
assert_equal(david.hasOwnProperty('name'), true);
assert_equal(david.hasOwnProperty('age'), true);
assert_equal(david.hasOwnProperty('sayHi'), false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment