一个对象可以有它的原型没有的属性吗?
Can an object have properties which its prototype doesn't have?
在 JavaScript 中,一个对象及其原型(即它的 属性 prototype
作为一个对象)必须具有完全相同的一组属性吗?
一个对象可以拥有其原型所没有的属性吗?
In JavaScript, must an object and its prototype (i.e. its property
prototype as an object) have exactly the same set of properties?
No. prototype
用于创建对象的实例。在创建实例的那一刻,实例成为一个独立于原型的对象,对它的修改不会影响原型(但是,对原型的更改会影响实例)。欢迎来到 prototypical inheritance!
Can an object have properties which its prototype doesn't have?
是,举个例子:
function foo(){
// doesn't matter what it does
}
let fooInstance = new foo();
console.log(foo.prototype.bar); // undefined
console.log(fooInstance.bar); // undefined
console.log("************************");
// Give the instance object a new property.
// This does not create a property on the instance's prototype
fooInstance.bar = "baz";
console.log(foo.prototype.bar); // undefined
console.log(fooInstance.bar); // baz
console.log("************************");
console.log(foo.prototype.hasOwnProperty("bar")); // false
console.log(fooInstance.hasOwnProperty("bar")); // true
如果您必须坚持使用原型,您可能 seal()
对象。
Object.seal()
方法密封一个对象,防止向其添加新属性并将所有现有属性标记为 non-configurable。当前属性的值仍然可以更改,只要它们是可写的。
您也可以 freeze()
对象,但这会阻止更改对象的任何部分。
在 JavaScript 中,一个对象及其原型(即它的 属性 prototype
作为一个对象)必须具有完全相同的一组属性吗?
一个对象可以拥有其原型所没有的属性吗?
In JavaScript, must an object and its prototype (i.e. its property prototype as an object) have exactly the same set of properties?
No. prototype
用于创建对象的实例。在创建实例的那一刻,实例成为一个独立于原型的对象,对它的修改不会影响原型(但是,对原型的更改会影响实例)。欢迎来到 prototypical inheritance!
Can an object have properties which its prototype doesn't have?
是,举个例子:
function foo(){
// doesn't matter what it does
}
let fooInstance = new foo();
console.log(foo.prototype.bar); // undefined
console.log(fooInstance.bar); // undefined
console.log("************************");
// Give the instance object a new property.
// This does not create a property on the instance's prototype
fooInstance.bar = "baz";
console.log(foo.prototype.bar); // undefined
console.log(fooInstance.bar); // baz
console.log("************************");
console.log(foo.prototype.hasOwnProperty("bar")); // false
console.log(fooInstance.hasOwnProperty("bar")); // true
如果您必须坚持使用原型,您可能 seal()
对象。
Object.seal()
方法密封一个对象,防止向其添加新属性并将所有现有属性标记为 non-configurable。当前属性的值仍然可以更改,只要它们是可写的。
您也可以 freeze()
对象,但这会阻止更改对象的任何部分。