Can I reference other properties during object declaration in JavaScript?
No. this
in JavaScript does not work like you think it does. this
in this case refers to the global object.
There are only 3 cases in which the value this
gets set:
The Function Case
foo();
Here this
will refer to the global object.
The Method Case
test.foo();
In this example this
will refer to test
.
The Constructor Case
new foo();
A function call that's preceded by the new
keyword acts as a constructor. Inside the function this
will refer to a newly
created Object
.
Everywhere else, this
refers to the global object.
Self-references in object literals / initializers
Well, the only thing that I can tell you about are getter:
var foo = { a: 5, b: 6, get c() { return this.a + this.b; }}
console.log(foo.c) // 11
How can a JavaScript object refer to values in itself?
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = { key1: "it ", key2: function() { return this.key1 + " works!"; }};
alert(obj.key2());
Javascript create reference to an object property?
Primitive types are immutable, so no, it's not possible. You can wrap your primitive type with an object, like this:
function MyNumber(n) { this.n = n; }
MyNumber.prototype.valueOf = function() { return this.n; }
var someObject = { a: 1, b: new MyNumber(2) };
var myRef = someObject.b;
MyNumber.call(myRef, myRef + 1);
console.log(+someObject.b); // convert to number with +
OR
var someObject = {
a: { value: 1 },
b: { value: 2 },
};
var myRef = someObject.b;
my_inc(myRef); // function my_inc (obj) { obj.value++; }
// someObject.b.value == 3
The React framework uses a very simple pattern to encapsulate values.
function Link(value, requestChange)
{
this.value = value;
this.requestChange = requestChange;
}
You can pass around the object, the current value can be accessed by inspecting the value property of the object, if you want to change it you can call requestChange
with a new value, you can change the value. The advantage would be to have the actual "storage location" and the logic for changing the value decoupled from the value read and write access. Note that the values can also be complex objects.
You could also achieve something similar with closures:
var someObject = {
a: 1,
b: 2
};
function property(object, prop) {
return {
get value () {
return object[prop]
},
set value (val) {
object[prop] = val;
}
};
}
var ref = property(someObject, "b");
ref.value; // 2
++ref.value; // 3
someObject.b; // 3
This works because the getter and setter functions have access to whatever bindings were in scope at the time of their creation (object
and prop
). You can now pass ref
around, store it in a data structure, etc.
How do I reference the same Object's properties during its creation?
It is not possible.
The object is not bound in any scope visible to EcmaScript expressions when the property values are evaluated.
Section 11.1.5 of the EcmaScript language spec explains how the object constructor syntax works.
The following describes how the object is created as a side-effect of evaluating the first property key value pair
The production
PropertyNameAndValueList : PropertyAssignment
is evaluated as follows:
- Let obj be the result of creating a new object as if by the expression
new Object()
whereObject
is the standard built-in constructor with that name.- Let propId be the result of evaluating PropertyAssignment.
- Call the [[DefineOwnProperty]] internal method of obj with arguments
propId.name
,propId.descriptor
, andfalse
.- Return obj.
Note that PropertyAssignment is evaluated after obj is created, but obj is never bound to any name accessible to an EcmaScript expression.
Only after all the property values are evaluated is anything assigned to o
or any other symbol in your program.
functions as a property in objects : referencing other properties inside of your function
You can do it using this
keyword
someObj = {
property : 44,
calculate : function(){
this.property * this.moreproperties;
};
if you have another function like callback for an event in jQuery store this
into variable
someObj = {
property : 44,
calculate : function(){
var parent = this;
$('#some-element').click(function() {
parent.something * parent.somethingElse
});
};
Typescript: How to reference other prop of literal object, from within the object?
Use a getter:
const Test = {
a: { someProp: true },
get b() {
return { ...Test.a, someOtherProp: true }
}
}
(This problem is not specific to TypeScript—it's how JavaScript works)
Pass-by-reference JavaScript objects
When you assign one variable to another, it's not that both those variables are now linked by reference; you're misunderstanding what "pass by reference" means here.
A variable holding an object does not "directly" hold an object. What it holds is a reference to an object. When you assign that reference from one variable to another, you're making a copy of that reference. Now both variables hold a reference to an object. Modifying the object through that reference changes it for both variables holding a reference to that object.
When you assign a new value to one of the variables, you're just modifying the value that variable holds. The variable now ceases to hold a reference to the object, and instead holds something else. The other variable still holds its reference to the original object, the assignment didn't influence it at all.
Related Topics
How to Write a Script to Edit a JSON File
R Networkd3 Package: Node Coloring in Simplenetwork()
How to Show Modal Window in Controller's Action
Wkwebkit JavaScript Execution When Not Attached to a View Hierarchy
How to Write Asynchronous Functions for Node.Js
What Is an Exclamation Point in JavaScript
Shiny: Start the App with Hidden Tabs, with No Delay
How to Get All Arguments of a Function as Single Object Inside That Function
Draggable Line Chart in R/Shiny
Syntaxerror: Unexpected Token Function - Async Await Nodejs
Remove Duplicates Form an Array
JavaScript Parseint() with Leading Zeros
Pure JavaScript Send Post Data Without a Form
Determine Which Element the Mouse Pointer Is on Top of in JavaScript