JavaScript - a unique property update in prototyped object literals

I'm only going to instantiate JavaScript objects using the prototype constructor, but I'm a little confused by the inheritance / reflection rules that apply to my case.

Essentially my problem is that the original object that is prototyped has several levels of properties / values:

var protoObj = {  
  prop1: {  
    first : 1,
    second : 2,
    third : {  
      a : 'foo',
      b : 'bar',
      c : {  
        'love': true,  
        'babies': false,
        'joy': undefined
      }
    } 
  },  
  prop2 : true       
};

... where all but a select few of these properties will remain unchanged (and must be dynamically updated) in all child objects.

I can update or create new top-level properties for child objects without really affecting the original prototype object:

if (typeof Object.create !== 'function') {
  Object.create = function(o){
    var F = function(){};
    F.prototype = o;
    return new F();
  };
}

var someObj = Object.create(protoObj);

someObj.prop2 = false;   
//protoObj.prop2 remains true

someObj.prop3 = [x,y,z];
//new property, unique to someObj (i.e. protoObj remains untouched)

, , 'joy' someObj, protoObj someObj :

someObj.prop1.third.c['joy'] = 'found';
//does not *directly* update someObj
//instead ends up setting the value of protoObj property 'joy' to be 'found'


someObj.prop1 = {
  first : 1,
  second : 2,
  third : {  
    a : 'foo',
    b : 'bar',
    c : {  
      'love': true,  
      'babies': false,
      'joy': 'found'
    }
  }
};
//explicitly sets the above values in someObj.prop1 (including 'joy'), but breaks
//the prototypal link back to protoObj for all data in someObj.prop1 as well

, , , . .

+3
2

: .

. , , JavaScript, "" -. , , . , :

var x = someObj.prop2;

someObj. prop2? , . prop2? , .

, . . :

someObj.prop2 = true;

, prop2 someObj true. , prop2, .

prop1 . someObj

var x = someObj.prop1;

prop1 -, someObj.

: propObj. , propObj. prop1, someObj, :

var someObj = Object.create(propObj);
someObj.prop1 = Object.create(propObj.prop1);
someObj.prop1.first = 42;

first someObj.prop1, propObj. , .

+2

, .

. , someObj.

, , :

JS () , , ( ).

, someObj.prop1, JS prop1 someObj, protoObj protoObj.prop1:

, , :

someObj.prop1.third.c['joy'] = 'found'

... , someObj.prop1 protoObj.prop1

, , , JS . , :

someObj.stuff.other = 3

JS someObj.stuff, .other .

:

someObj.stuff = 3

JS -!! 3 someObj someObj .

, .

, JS . . :

function MyObj() {
  this.prop1 = {first: 1, second: 2, third: {a: ...} }
  this.prop2 = true;
}

, , protoObj.

"" ( ) JavaScript.

+1

Source: https://habr.com/ru/post/1789388/


All Articles