Skip to content

Instantly share code, notes, and snippets.

@ositowang
Created April 5, 2019 16:49
Show Gist options
  • Save ositowang/132b404e1abaea23f8b5862ef294475e to your computer and use it in GitHub Desktop.
Save ositowang/132b404e1abaea23f8b5862ef294475e to your computer and use it in GitHub Desktop.
prototype based inheritance in js
/**
* The hack es5 object.create() gives us. We make a shallow copy of the object
* passed in and returned the new object with prototype linked to the passed in
* object
* 1. still we have the shared reference problems
*/
//simple version of object.create()
function objectCreate(obj) {
function F() {}
F.prototype = obj;
return new F();
}
var person = {
name: 'Tom',
friends: ['Daday', 'Mommy', 'Didi'],
};
var anotherPerson = object(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Rob');
var yetAnotherPerson = object(person);
yetAnotherPerson.name = 'Linda';
yetAnotherPerson.friends.push('Barbie');
alert(person.friends); //""Daday", "Mommy", "Didi","Rob", barbie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment