Created
April 5, 2019 16:49
-
-
Save ositowang/132b404e1abaea23f8b5862ef294475e to your computer and use it in GitHub Desktop.
prototype based inheritance in js
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
/** | |
* 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