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.
You can simply do it by using:
Then use it like:
This well result in:
This will make extend your properties create a new Object with the object parameter prototypes without altering the passed object.
But if you want to extend your Object without modifying it parameters, you can add extendProperty to your object.
Summary:
Javascript uses a mechanism which is called prototypal inheritance. Prototypal inheritance is used when looking up a property on an object. When we are extending properties in javascript we are inheriting these properties from an actual object. It works in the following manner:
myObj.foo
ormyObj['foo']
) the JS engine will first look for that property on the object itselfWhen we want to extend from a object in javascript we can simply link this object in the prototype chain. There are numerous ways to achieve this, I will describe 2 commonly used methods.
Examples:
1.
Object.create()
Object.create()
is a function that takes an object as an argument and creates a new object. The object which was passed as an argument will be the prototype of the newly create object. For example:2. Explicitly setting the prototype property
When creating objects using constructor functions, we can set add properties to its prototype object property. Objects which are created form a constructor function when using the
new
keyword, have their prototype set to the prototype of the constructor function. For example:PLEASE ADD REASON FOR DOWNVOTE
No need to use any external library to extend
In JavaScript, everything is an object (except for the three primitive datatypes, and even they are automatically wrapped with objects when needed). Furthermore, all objects are mutable.
thanks to ross harmes , dustin diaz
Edit:
Before using the code, please check the comments from user2491400 that reports about the side effects of simply assigning to
prototype
.Original answer:
You want to 'inherit' from Person's prototype object:
In the majority of project there are some implementation of object extending: underscore, jquery, lodash: extend.
There is also pure javascript implementation, that is a part of ECMAscript 6: Object.assign: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign