suhas tangadle
suhas tangadle

Reputation: 39

Object.create() functioning

var task = {};

task.prop1 = "prop1 value";
task.prop2 = "prop2 value";

console.log(task);

var newTask = Object.create(task);

console.log(newTask);

In this case, why is newTask printing empty? As I understand it, shouldn't it print the properties of task?

Edit: I found out that when we create the object through Object.create(task), we are assigning newTask's prototype as task, hence new task does not have the native task object's proprties which can be verified via getOwnProperty() on the newTaskObject. But when we carefully examine, when we try to access the properties of task object through newTask, the prototype chain is rolled up and we dont get undefined. Please correct me if I am wrong.

Upvotes: 0

Views: 46

Answers (3)

vsvk
vsvk

Reputation: 59

Object.create() method creates a new object, using an existing object to provide the newly created object's __proto__. You can refer to either newTask.prop1 or newTask.__proto__.prop1

Upvotes: 0

Rushikesh Bharad
Rushikesh Bharad

Reputation: 1010

I think you are looking for this

var task = function() {
  this.prop1 = "prop1 value";
  this.prop2 = "prop2 value";
}

var newTask = new task();

console.log(newTask);

Javascript can create an instance of a function which is treated as a class.

Upvotes: 0

Ry-
Ry-

Reputation: 224913

You can read the properties of task through it – try console.log(newTask.prop1) – but your browser’s console only lists own properties when summarizing objects.

Expand it to see the prototype:

Screenshot of expanded object in Firefox console

Upvotes: 2

Related Questions