| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/create | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
O mtodo Object.create() cria um novo objeto, utilizando um outro objeto existente como prottipo para o novo objeto a ser criado.
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
},
};
const me = Object.create(person);
me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // Inherited properties can be overwritten
me.printIntroduction();
// Expected output: "My name is Matthew. Am I human? true"
Object.create(proto[, propertiesObject])
protoO objeto que deve ser o prottipo do objeto recm-criado.
propertiesObjectOpcional. Se especificado e no undefined, um objeto cuja as propriedades prprias enumerveis (isto , aquelas propriedades definidas sobre si mesmo, e no propriedades enumerveis ao longo da sua cadeia prottipa) especificam os nomes das propriedades a serem adicionadas ao objeto recm-criado, com os nomes das propriedades correspondentes. Essas propriedades correspondem ao segundo argumento de Object.defineProperties().
Um novo objeto com o prottipo de objeto e propriedades especificadas.
Uma exceo TypeError se o parmetro proto no for null ou um objeto.
Object.create()A seguir, um exemplo de como usar Object.create() para realizar uma herana tradicional. Isto para herana simples, que a nica herana suportada pelo JavaScript.
// Shape - superclasse
function Shape() {
this.x = 0;
this.y = 0;
}
// mtodo da superclasse
Shape.prototype.move = function (x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
// Rectangle - subclasse
function Rectangle() {
Shape.call(this); // chama construtor-pai.
}
// subclasse extende superclasse
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log("Rect uma instncia de Rectangle?", rect instanceof Rectangle); // true
console.log("Rect uma instncia de Shape?", rect instanceof Shape); // true
rect.move(1, 1); // Sada: 'Shape moved.'
Caso queira realizar herana de mltiplos objetos, ento mixins ("mistura") so uma possibilidade.
function MyClass() {
SuperClass.call(this);
OtherSuperClass.call(this);
}
MyClass.prototype = Object.create(SuperClass.prototype); // herana
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin
MyClass.prototype.myMethod = function () {
// faz algo
};
A funo mixin copia as funes do prottipo da superclasse para o prottipo da subclasse, a funo mixin precisa ser fornecida pelo usurio. Um exemplo de uma funo do tipo mixin seria jQuery.extend().
propertiesObject com Object.create()var o;
// cria um objeto com prottipo null
o = Object.create(null);
o = {};
// equivalente a:
o = Object.create(Object.prototype);
// Exemplo em que criamos um objeto com algumas propriedades
// (Note que o segundo parmetro mapeia as chaves para *descritores de propriedade*.)
o = Object.create(Object.prototype, {
// foo uma 'propriedade de valor' ('value property') normal
foo: { writable: true, configurable: true, value: "hello" },
// bar uma propriedade getter-setter (accessor)
bar: {
configurable: false,
get: function () {
return 10;
},
set: function (value) {
console.log("Setting `o.bar` to", value);
},
/* com os ES5 Accessors nosso cdigo pode ser escrito como:
get() { return 10; },
set(value) { console.log('setting `o.bar` to', value); } */
},
});
function Constructor() {}
o = new Constructor();
// equivalente a:
o = Object.create(Constructor.prototype);
// Claro, se h de fato um cdigo de inicializao na funo
// Constructor, o Object.create() no pode refleti-la
// Cria um novo objeto cujo protptipo um objeto novo, vazio
// e adiciona a propriedade 'p' com o valor 42.
o = Object.create({}, { p: { value: 42 } });
// por padro, propriedades NO SO escritas, enumeradas ou configurveis:
o.p = 24;
o.p;
// 42
o.q = 12;
for (var prop in o) {
console.log(prop);
}
// 'q'
delete o.p;
// false
// especificar uma propriedade ES3
o2 = Object.create(
{},
{
p: {
value: 42,
writable: true,
enumerable: true,
configurable: true,
},
},
);
Este polyfill cobre o caso de uso principal que a crio de um novo objeto em que o prottipo foi escolhido mas no leva em considerao o segundo argumento.
Note que, enquanto a configurao null as [[Prototype]] suportada no ES5 Object.create, este polyfill no suporta devido limitao inerente em verses do ECMAScript inferiores a 5.
if (typeof Object.create != "function") {
Object.create = (function () {
var Temp = function () {};
return function (prototype) {
if (arguments.length > 1) {
throw Error("Second argument not supported");
}
if (typeof prototype != "object") {
throw TypeError("Argument must be an object");
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-object.create |
Object.defineProperty()Object.defineProperties()Object.prototype.isPrototypeOf()This page was last modified on 17 de fev. de 2025 by MDN contributors.
ObjectObject.assign()Object.create()Object.defineProperties()Object.defineProperty()Object.entries()Object.freeze()Object.fromEntries()Object.getOwnPropertyDescriptor()Object.getOwnPropertyDescriptors()Object.getOwnPropertyNames()Object.getOwnPropertySymbols()Object.getPrototypeOf()groupBy()Object.hasOwn()Object.is()Object.isExtensible()Object.isFrozen()Object.isSealed()Object.keys()Object.preventExtensions()Object.seal()Object.setPrototypeOf()Object.values()Object.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |