Object.create() functioning

时间:2018-04-18 18:05:50

标签: javascript

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.

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我认为你正在寻找这个

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

var newTask = new task();

console.log(newTask);

Javascript可以创建一个被视为类的函数实例。

答案 2 :(得分:0)

Object.create()方法使用现有对象创建新对象,以提供新创建的对象__proto__。您可以参考newTask.prop1newTask.__proto__.prop1