为什么两个Object.create()调用导致合并?

我不明白如何在JavaScript中使用Object.create()。 为什么在这个代码中,两个对象a和b合并,而他们是在两个不同的上下文中声明的呢?

var l = { a: null, b: null } function a() { var a = Object.create(l); aa = "a"; console.log('a : ', aa, ab); } function b() { var b = Object.create(l); bb = "b"; console.log('b : ' + ba, bb); } function main() { a(); b(); } main(); 

这是输出:

 a : a null b : ab 

我如何隔离他们?

我想你错误Object.createObject.assign东西:

 // This is not what you want var a = Object.create(l); // Do this instead var a = Object.assign({}, l); 

如果你希望函数的对象是“孤立的”(我猜你是在说没有副作用),你想创build新的对象,例如使用Object.assign (而不是Object.create )。

Object.create的目的是基于参数的原型创build一个新的对象, 在这里看到更多的信息。 在运行OP的源代码时,我发现结果令人惊讶; 你自己看:

 var l = { a: null, b: null } function a() { var a = Object.create(l); aa = "a"; console.log('a : ', aa, ab); } function b() { var b = Object.create(l); bb = "b"; console.log('b : ' + ba, bb); } function main() { a(); b(); } main();