繁体   English   中英

使用Object.create(name)与Object.create(name.prototype)进行Object.Create

[英]Object.Create with Object.create(name) vs Object.create(name.prototype)

我正在学习JavaScript,并且正在尝试了解主要区别。 我可以创建对象Object.create(someName)我可以创造Object.create(someName.prototype)但我不太明白的主要区别。 我应该将属性作为常规属性吗? someName.asomeName.prototype.a吗? 这一点让我感到困惑。 我了解使用Object.Create im定义对象原型时使用对象im进行someName但是我可以指定someNamesomeName.prototype但是我似乎无法完全理解它们之间的区别和最佳实践。 非常感谢您的帮助。 :)

Object.create创建一个新对象,其原型是作为整个函数的第一个参数传递的原型。

在JavaScript中, prototype属性是具有特殊功能的常规对象,但是正如我已经说过的,它仍然是常规对象

因此, 何时使用x或x.prototype的问题取决于您的要求。

例如:

var obj = { name: "Matías" };

// This will create a new object whose prototype
// is the object contained in the "obj" variable
var obj2 = Object.create(obj);

实际上,对象不拥有prototype属性。 当您想从某个构造函数的原型创建对象时,可以使用其他方法:

var A = function() {};
A.prototype.doStuff = () => {
    // do stuff here
};

// A common mistake is to provide A instead of A.prototype.
// In JavaScript, even functions are objects, hence if you provide
// A instead of A.prototype, the prototype of the newly created object
// will be the function A and its members, not the ones that would be available
// creating an object like this: new A()
var B = Object.create(A.prototype);
B.doStuff();

var C = Object.create(A);
// Function "doStuff" is undefined!!
C.doStuff();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM