Can a JavaScript object property refer to another property of the same object? [duplicate]

Asked
Active3 hr before
Viewed126 times

8 Answers

duplicatejavascriptpropertyobject
90%

Meta Stack Overflow , Stack Overflow help chat ,Stack Overflow en español,Stack Overflow на русском

Not with object literals (this has the same value during constructing of the literal that it did before-hand). But you can do

var carousel = new(function() {
   this.$slider = $('#carousel1 .slider');
   this.panes = this.$slider.children().length;
})();
load more v
88%

It might seem that the line (*) would cause an error, but it does not. The value of user is constant, it must always reference the same object, but properties of that object are free to change.,One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, booleans, etc – are always copied “as a whole value”.,So, copying an object variable creates one more reference to the same object.,An important side effect of storing objects as references is that an object declared as const can be modified.

let message = "Hello!";
let phrase = message;
load more v
72%

I recently tried to create an object like this:,Is there a way for properties of an object to refer to other properties of the same object, while that object is still being declared?,This uses an object created from an anonymous function constructor.,Not with object literals (this has the same value during constructing of the literal that it did before-hand). But you can do

I recently tried to create an object like this:

var carousel = {
   $slider: $('#carousel1 .slider'),
   panes: carousel.$slider.children().length
};

This makes sense, since I'd assume that carousel isn't fully declared until the assignment statement has been fully executed. However, I'd like to avoid resorting to this:

var carousel = {};
carousel.$slider = $('#carousel1 .slider');
carousel.panes = carousel.$slider.children().length;

Based on Matthew Flaschen and casablanca's answers (thanks, guys!), I think these are the versions of my actual code that I'd end up with, based on each approach:

// Matthew Flaschen

var carousel = new(function() {
   this.$carousel = $('.carousel');
   this.$carousel_window = this.$carousel.find('.window');
   this.$carousel_slider = this.$carousel.find('.slider');
   this.$first_pane = this.$carousel.find('.slider').children(':first-child');
   this.panes = this.$carousel_slider.children().length;
   this.pane_gap = this.$first_pane.css('margin-right');
})();

and

// casablanca

var $carousel = $('.carousel'),
   $carousel_slider = $carousel.find('.slider'),
   $first_pane: $carousel.find('.slider').children(':first-child');

var properties = {
   $carousel_window: $carousel.find('.window'),
   panes: $carousel_slider.children().length,
   pane_gap: $first_pane.css('margin-right')
};

properties.$carousel = $carousel;
properties.$carousel_slider = $carousel_slider;
properties.$first_pane = $first_pane;
load more v
65%

If the source value is a reference to an object, it only copies the reference value., For deep cloning, we need to use alternatives, because Object.assign() copies property values. , The target object — what to apply the sources’ properties to, which is returned after it is modified. ,The source object(s) — objects containing the properties you want to apply.

Object.assign(target, ...sources)
load more v
75%

property b is a non-enumerable property.,This fixes the issue we had earlier. Now newObj.b has a copy and not a reference! This is a way to deep copy objects. Here’s an example:,Note: Properties on the prototype chain and non-enumerable properties cannot be copied. See here:,Property descriptors are not copied. A “writable” descriptor with value set to be false will be true in the objCopy object.

As you know, the assignment operator doesn’t create a copy of an object, it only assigns a reference to it, let’s look at the following code:

let obj = {
   a: 1,
   b: 2,
};
let copy = obj;

obj.a = 5;
console.log(copy.a);
// Result 
// a = 5;
load more v
40%

To shallow copy, an object means to simply create a new object with the exact same set of properties. We call the copy shallow because the properties in the target object can still hold references to those in the source object.,Here we create a new object and copy every property from the source object.,When we make a deep copy we create a completely new object which holds no references to the original.,Note: Merging actually doesn’t lose references to sources. If we wanted to lose them we could create a deep copy of a merged object.

Tests

const testShallow = (shallowFn: ShallowFn) => {
   const obj1 = {
      prop1: true,
      prop2: {
         prop3: true
      }
   }
   const copiedObj1 = shallowFn(obj1)
   expect(copiedObj1).not.toBe(obj1)
   expect(copiedObj1.prop2).toBe(obj1.prop2)
   expect(copiedObj1).toEqual(obj1)
}
describe('shallow v1 (spread operator)', () => {
   it('copies an object shallowly', () => {
      return testShallow(shallowv1)
   })
})
describe('shallow v2 (copy props)', () => {
   it('copies an object shallowly', () => {
      return testShallow(shallowv2)
   })
})
load more v
22%

Nearly everything in JavaScript is an object other than six things that are not objects which are — null,undefined, strings, numbers, boolean, and symbols. These are called primitive values or primitive types.,In JavaScript think of an object as a list that contains items, and each item (a property or a method) in the list is stored by a key-value pair in memory as reference.,JavaScript objects are somewhat different in the way they are created. There is no requirement for a class as such and can be declared using literal notation.,Object literal (D\direct way). Object literals are a comma-separated list of key-value pairs wrapped in curly braces. Object literal property values can be of any data type, including array literals, functions, nested object literals or primitive data type.

Let’s see an object example.

const firstObj = {
   1: "deepak",
   "age": 28
}
load more v
60%

The contents of an object are called properties (or members), and properties consist of a name (or key) and value. Property names must be strings or symbols, and values can be any type (including other objects).,Like all JavaScript variables, both the object name (which could be a normal variable) and the property name are case sensitive. You access the properties of an object with a simple dot-notation.,When destructuring an object the variable names and the object property names must match.,Properties can also be accessed by using a string value that is stored in a variable. In other words, the object’s property key can be a dynamic value. For example: a variable. The said concept is illustrated in the following example.

Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object.

var identifier = {
   Key1: value,
   Key2: function() {
      //functions 
   },
   Key3: [“content1”, ”content2”]
}
load more v

Other "duplicate-javascript" queries related to "Can a JavaScript object property refer to another property of the same object? [duplicate]"