JavaScript:我们使用Object.create时最大的优势是什么
JavaScript: what is the most advantage that we got when we use Object.create
我们可以简单地分配一个值而不是使用 Object.create 吗?
Rectangle.prototype = Shape.prototype;
Rectangle.prototype =
Object.create(Shape.prototype)
以上两种说法有什么区别?
Object.create() 方法创建一个新对象,使用现有对象提供新创建对象的 proto 。所以,如果你直接给一个对象赋值,那么被赋值的对象也有可能发生变异,这里是一个例子。
let k = {a:12, b:34};
let j = k;
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "Mutated";//Updating j changes k too
console.log(`k after mutation ${JSON.stringify(k)}`);
其中 Object.create 不会变异
let k = {a: 123, b: 34};
let j = Object.create(k);
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "this won't mutate k";
console.log(`k after mutation ${JSON.stringify(k)}`);
我们可以简单地分配一个值而不是使用 Object.create 吗?
Rectangle.prototype = Shape.prototype;
Rectangle.prototype =
Object.create(Shape.prototype)
以上两种说法有什么区别?
Object.create() 方法创建一个新对象,使用现有对象提供新创建对象的 proto 。所以,如果你直接给一个对象赋值,那么被赋值的对象也有可能发生变异,这里是一个例子。
let k = {a:12, b:34};
let j = k;
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "Mutated";//Updating j changes k too
console.log(`k after mutation ${JSON.stringify(k)}`);
其中 Object.create 不会变异
let k = {a: 123, b: 34};
let j = Object.create(k);
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "this won't mutate k";
console.log(`k after mutation ${JSON.stringify(k)}`);