var Parent = {};
var child = Object.create(parent);
上面的代码块和下面的代码块一样吗?
var Parent = {};
var child = new Parent();
如果不是 Object.create 做什么?
最佳答案
is the above block of code as same as below?
没有。您的第二个示例会导致运行时错误,因为您尝试将某些内容作为函数调用,但实际上它不是函数。
if not what the Object.create thingy do?
Object.create
创建一个新对象,并将您提供的对象设置为新对象的原型(prototype)。示例:
var a = {foo: "bar"};
var b = Object.create(a);
console.log(b.foo); // "bar", because `b` gets `foo` via its prototype
console.log("foo" in b); // true, because `b` gets `foo` via its prototype
console.log(b.hasOwnProperty("foo")); // false, the property is on its prototype
Object.create
还有第二个参数,它允许您定义正在创建的对象的属性, details on MDN (当然)在 the specification .
如果您想重复使用 new Xyz
来创建共享公共(public)原型(prototype)和初始化的对象(通常称为对象的“类”,但该术语在 JavaScript 中非常宽松),您可以这样做通过编写一个函数(当您将其与new
一起使用时称为“构造函数”)并将对象应共享的内容分配给YourFunction.prototype
,这是 new
运算符将分配给对象作为其原型(prototype)的内容(就像 Object.create
从您提供的参数分配原型(prototype))。例如:
function Thingy() {
}
Thingy.prototype.foo = "bar";
var a = new Thingy(); // 1. Creates new object
// 2. Assigns `Thingy.prototype` as the prototype
// 3. Calls Thingy with `this` referencing the new object
console.log(a.foo); // "bar" because it gets it from its prototype
有构造函数的用例,也有使用 Object.create
的用例。 JavaScript 的伟大之处在于两者兼而有之。
关于javascript - Javascript 中的 object.create 语法用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20595849/