I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do.
I've seen several people on the internet use a method called extend on object. The code will look like this:
var Person = {
name : 'Blank',
age : 22
}
var Robot = Person.extend({
name : 'Robo',
age : 4
)}
var robot = new Robot();
alert(robot.name); //Should return 'Robo'
Does anyone know how to make this work? I've heard that you need to write
Object.prototype.extend = function(...);
But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.
People who are still struggling for the simple and best approach, you can use
Spread Syntax
for extending object.Note: Remember that, the property is farthest to the right will have the priority. In this example,
person2
is at right side, sonewObj
will have name Robo in it.Different approach: Object.create
Per @osahyoun answer, I find the following as a better and efficient way to 'inherit' from Person's prototype object:
Create new instances:
Now, by using Object.create:
Check also the MDN documentation.
Mozilla 'announces' object extending from ECMAScript 6.0:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends
NOTE: This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal.
This technology is available in Gecko (Google Chrome / Firefox) - 03/2015 nightly builds.
You might want to consider using helper library like underscore.js, which has it's own implementation of
extend()
.And it's also a good way to learn by looking at it's source code. The annotated source code page is quite useful.