4 ms·
An object 'a' having a prototype of 'b' means that if a property is not found on 'a', it will then look it up on 'b'. It's just chaining. To set an object's pro
by Jasper_ 4y ago
An object 'a' having a prototype of 'b' means that if a property is not found on 'a', it will then look it up on 'b'. It's just chaining. To set an object's prototype, you set the special __proto__ property on it.
var a = { foo: 5 };
a.__proto__ = { foo: 10, bar: 2 };
console.log(a.foo, a.bar); // 5, 2
You can also use Object.create() to initialize an object with a given prototype. So the above is equivalent to:
var a = Object.create({ foo: 10, bar: 2 });
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The real confusing part is the property called "prototype". This doesn't exist on random objects, it's only available on functions, and it sets the __proto__ of the object created with that function when used as a constructor (that is, when using the "new" operator).
function Foo() {}
Foo.prototype = { foo: 10, bar: 2 };
var a = new Foo();
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The "new" operator also sets a.constructor = Foo, and calls the constructor method. You can think of the new operator as syntax sugar performing the below:
function Foo() {}
Foo.prototype = { foo: 10, bar: 2 };
// The four lines below are equivalent to `var a = new Foo();`
var a = {};
a.constructor = Foo;
a.__proto__ = Foo.prototype;
Foo.call(a);
a.foo = 5;
console.log(a.foo, a.bar); // 5, 2
The reason for all of these different mechanisms is history. The original mechanism was the constructor `prototype`, then in ES5, Object.create() was added. Then, much later on, `__proto__` was standardized (it was a non-standard extension before).
- brianzelip 4y agofunction Foo() {} Foo.prototype = { foo: 10, bar: 2 }; var a = new Foo(); console.log(a.foo, a.bar); // 5, 2 Isn’t your logged a.foo wrong? a.foo === 10, right?
- Jasper_ 4y agoOops, I forgot to add the `a.foo = 5;` line like I had in the other examples. Fixed.
- deleted 4y ago[deleted]