obj newobj ?
, , , ( constructor) Object.prototype. Object.prototype:
, obj:
+----------+
Object.prototype-------------+--->| toString |
| | valueOf |
| | ... |
| +----------+
+---------------+ |
obj---->| [[Prototype]] |----+
| a: 5 |
+---------------+
. newObj:
+----------+
Object.prototype--------------------------------------+--->| toString |
| | valueOf |
| | ... |
| +----------+
+---------------+ |
differentInit.prototype------+--->| [[Prototype]] |---+
| +---------------+
|
|
+---------------+ |
newObj->| [[Prototype]] |----+
| a: 5 |
+---------------+
( , Oriol , , Object.prototype differentInit.prototype , constructor, Object differentInit . , obj.constructor Object, newObj.constructor differentInit. , ...)
- differentInit.prototype, .
json, , JSON . JSON - . , JSON.
, Object.create().
JavaScript , Object.create(null) ( null [[Prototype]], , ).
... ?
:
, . obj = {}, Object.prototype .
new ; , prototype, , new. , function ( class), prototype ; . ( prototype null, new Object.prototype.)
, , new, , function:
function Foo() {
}
Foo.prototype.bar = function() {
console.log("Foo instance says 'bar'!");
};
var f = new Foo();
f.bar();
ES2015, , class:
class Foo {
bar() {
console.log("Foo instance says 'bar'!");
}
}
var f = new Foo();
f.bar();
, : Foo, new, Foo.prototype bar .
Object.create(p), p . # 2 , p null , . ES5, ( null). ( , .)
:
Reflect.setPrototypeOf(target, proto) Object.setPrototypeOf(target, proto), ES2015. ( , Reflect.setPrototypeOf , - target; Object.setPrototypeOf , . JavaScript Reflect, .)
( ) __proto__ , ( ) Object.prototype. :
. JavaScript -.
. ES2015.
. ES2015, - , Object.prototype, , Reflect.setPrototypeOf.
, , ?
"" new differentInit, , . , ( "" , , ). Object.create ( new). , , , Object.create - .