This is a prototype. How to get it?

A. prototype =
{
subO:
{
 f: function ()
{
 this // will Return subO
 // How to prototype this?
}
}
};
September 26th 19 at 11:46
3 answers
September 26th 19 at 11:48
No way. Nested objects will simply remain embedded objects, in fact you have declared a container for static variables.
function MyObject() {
}

MyObject.prototype = {
 sub: {},
}

var a = new MyObject(),
 b = new MyObject();

a.sub.test = 'foo';
b.sub.test === 'foo';


Actually according to this the data initialization should be done in the constructor.
September 26th 19 at 11:50
You can, of course, poizvraschatsya with getters / setters from ES5

function A(){}
var subO = {
 f: function(){
 return this.that;
}
}
A. prototype = {
 get subO(){
 var P = Object.create(subO);
 P. that = this;
 return P;
}
}

var inst = new A;
inst.subO.f() === inst; // true

or proxies from ES6, but it's easier and better to bind the context in the constructor:

function A(){
 this.subO = {
 f: function(){
 return this;
}.bind(this)
}
}
var inst = new A;
inst.subO.f() === inst; // true
September 26th 19 at 11:52
Strictly speaking, it is still possible to directly pass the context to the function, forcing her to handle it this is exactly the desired object:
// object prototype;
var A = {
 x: 10,
 f: function() {
console.log(this.x);
}
}
// the heir;
var sub0 = Object.create(A); // A prototype for sub0;
// override;
sub0.x=20;
// magic JS =)
sub0.f() // 20

sub0.f.apply(A) // call in context of the prototype, it returns 10;

Find more questions by tags JavaScript