0
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.

1
  • console.log for both values print the same object. newTask is not empty if you check correctly. Commented Apr 18, 2018 at 18:09

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.