Atul Agrawal
Atul Agrawal

Reputation: 1520

JavaScript's Object.create method

i have created an object as follows

 var lassie = {
 name: 'Lassie',
 breed: 'Collie',
 speak: function () {
 return 'Woof! Woof!'; }
 };

I create another object by using Object.create method of javascript as

var obj = Object.create(lassie);

now when i console obj it gives me a blank object. But when i console obj.speak() it gives me 'Woof! Woof!' .

can someone please explain why?

Upvotes: 1

Views: 74

Answers (4)

Hardik Munjaal
Hardik Munjaal

Reputation: 93

var lassie = {
 name: 'Lassie',
 breed: 'Collie',
 speak: function () {
 return 'Woof! Woof!'; }
 };

var obj = Object.create(lassie);

Now your concern is now when You console obj it gives me a blank object. But when you console obj.speak() it gives you 'Woof! Woof!' .

Actually here obj has now all the properties of lassie ,but these are not the obj own properties.

Here you will see all the properties of obj:

for(var a in obj){
     console.log(a);
     }

Here you will see obj's own property:

for(var b in obj){
    if (obj.hasOwnProperty(b)) {    
         console.log(b);
    }
 }

This is actually because when we use var target = Object.create(obj); then all the properties are added to target as a prototype properties.

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Basically Object.create will create an object that would have no own properties. That means the passed object's own properties would be assigned as the prototype properties of the newly created object and that would be returned.

A sample structure of the object returned from Object.create(),

var obj = {a:10};
var obj1 = Object.create(obj);
console.log(obj1); // {... __proto__ : {a : 10 ...}}

If you want to copy the own propties(enumerable) of the passed object to another one object, then you have to can Object.assign(obj) as an alternate to passing second parameter as property descriptor properties for Object.create

Upvotes: 1

guest271314
guest271314

Reputation: 1

Pass lassie as first parameter to Object.create() to set prototype of obj to lassie; iterate lassie return properties as second parameter

var lassie = {
   name: 'Lassie',
   breed: 'Collie',
   speak: function() {
     return 'Woof! Woof!';
   }
 };

 var obj = Object.create(lassie, (function() {
   var _obj = {};
   for (var prop in lassie) {
     _obj[prop] = {
       value: lassie[prop],
       writable: true,
       enumerable: true,
       configurable: true
     }
   }
   return _obj
 }()));

alert(obj.speak())

Upvotes: 1

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

var obj = Object.create(lassie);

By doing this you have created a new object which inherits the properties from lassie.

if you do

obj.name; //this prints "Lassie" too.

Upvotes: 1

Related Questions