Reputation: 39
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
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
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
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:
Upvotes: 2