How to get the object "address" in javascript? - javascript

Well, I am not sure if I describe the problem clearly, currently I am using ExtJS to do some developing, I saw some objects are "singleton", such as "Ext.Viewport", In C++, I can get the address of the object to see if they are actually same object, in Python, I can use "id" function to get the hash code of the object, and In Java I have similar built-in function "hashCode" to check if the objects are really same object, is there similar ways in javascript for this? so if there are some functions or operator in javascript, then I can tell if the object in ExtJS defined as "singleton" is really referencing to the same object.

You don't need anything so complicated. If two values are the same object, then they will be equal.
var foo = {};
var bar = foo;
alert(foo == bar);
If they are different (even if identical) objects, they won't be.
var foo = {};
var bar = {};
alert(foo == bar);

Your question is not very clear, but I'll try to answer.
Javascript itself does not use unique identifiers for each object by default. You could add this if you wanted to.
Depending on your requirements, you could also use the typeof operator to compare the type.
ExtJs however, does use unique id's (either id or itemId) and also allows you to get the class name of the object that your using. So you could do this easily in ExtJs.
The answer depends on whether you are comparing the type of object, or the actual object instance itself.
This other SO answer may be beneficial

I think that I'm understanding you... but, did you check this JavaScript comparator ?
=== - equal value and equal type
!== - not equal value or not equal type
reference: Javascript comparators

If you want to know if two object references refer to the same single object instance, use ==.
If you want to do a deep comparison of the referenced objects to see if the objects contain all the same values, even if they are not the same object instance, use Lodash's _.isEqual(a, b) method.

could also convert both to json, and use something like jsonDiff: https://github.com/pkafel/json-diff

Related

What is the purpose of comparing two objects? (as opposed to primitives)

I'm currently learning Javascript (I'm familiar with C# and Python), and currently the tutorial I'm reading is discussing comparison between two objects. In the coding I've done (I've had various projects), this sort of thing has never really been needed. Given that this might be important for the future, I thought I'd look for when/where to use object comparison, but all I can find are questions/answers on how it works, not why you should use it and when. I can't think of any situations off the top of my head where comparisons between primitives wouldn't be better, so any help in this area would be appreciated.
You would use it when you have two variables which refer to objects, and you want to see whether they refer to the same object. For example, with the window object, you can do
if (window !== window.top) {
console.log('This script must be running in an iframe!');
}
I can't think of any situations off the top of my head where comparisons between primitives wouldn't be better
Many objects (including window) can't just be converted to a unique primitive easily.
You may be able to use JSON.stringify to convert a plain object to a string, and then compare those strings, but this won't help you compare whether the objects are actually the same object in memory:
const obj1 = { prop: 'val' };
const obj2 = { prop: 'val' };
// They are not the same object
console.log(obj1 === obj2);
// But if you convert them to a primitive string first, you won't be able to tell
console.log(JSON.stringify(obj1) === JSON.stringify(obj2));
At the risk of a circular argument, you use it when you need to use it. :-)
I'd say it's roughly the same as in C#. In both cases, when you use an equality operator, it tests to see whether they're the same object (rather than separate but equivalent objects).
For instance, suppose you have an array of objects, and the contents of that array can change. Later, you have an object you should remove. You'd compare the object to remove with the objects in the array to see if you should remove it (often in a filter operation):
arrayOfObjects = arrayOfObjects.filter(obj => obj !== objToRemove);

How is better to check parameters object in javascript?

Most of time I use something like this:
function(obj) {
obj = obj || {};
// do stuff
var foo = obj.foo;
}
But my coworkers played a little bit with console.time/timeEnd and ensured me that
if (obj)
var foo = obj.foo;
is faster (code may be more complicated, it's only example).
But, as for me, 1st variant looks better. But we created additional empty object every time (when no parameters passed). I would like to hear what do you think guys. What method do you use?
The first method is appropriate when you need a valid object in obj for the rest of your code and you want to assure there is a valid object in just one place in the code.
The second method is appropriate when you just want to check if obj was passed or not and do something different in your code depending upon that condition. A more robust check would be:
if (typeof obj === "object")
So, these are different techniques that accomplish different goals and are mostly used in different circumstances.
So, the answer is that "it depends upon what the rest of your code is doing and on what you're really trying to accomplish in your code". There is no one answer that is always correct.
A common design pattern for your first technique is used when you have an optional object with optional properties and you want to fill in default values for missing properties or even if the whole object was not passed:
function doSomething(obj) {
var defaults = {timeout: 2000, caseSensitive: false, waitTime: 400};
var options = Object.assign({}, defaults, obj);
// safely use options object in the rest of this function
}
This technique also safely works on a copy of the passed object so the caller's object is never modified.
The first one is slower because if obj is missing it will go through creating an object. The second one just does an check and an assignment so it will be quicker but you won't have the presence of obj. If you ever depend on the presence of obj then use the first one, if you just refer to foo then use the second one.
However...in all honesty you shouldn't fret over optimizations like this, instead do what you feel is clearer and easier to read.
I would recommed to use the second method for checking whether object is defined or not. A better way would be to check for object that i think is
if(typeof object !== undefined)
as it gives a clear understanding what we are trying to do in the if block

What is the correct way to initialise an empty property of an object in JavaScript

I have an object that with properties, 1 of those properties prop2 will only be initialised later and added to this object when its ready.
I want to show it as a property of the object purely for human readability so that when I look at the code later I will know that it exists and will/can be used.
So my question is what is:
What is the correct way to initialise an empty property of an object
in JavaScript
myObject = {
prop1: 'somevalue',
prop2: '' <---- ''|null|undefined|false|0|{} what is correct
}
I am assuming it depends on the type that will be used, and I realise that anything actually works, I am interested in the best practice way.
Fiddler: http://jsfiddle.net/gamelodge/DWCEa/
I usually use null for this purpose. It is distinct from undefined (does not exist) and satisfies the requirement that the variable exists but has no value.
The usual way is to use null.
undefined would work as well, but a) it's longer b) it's not a keyword c) too many people use typeof to test for property existence. It also has a little different notion.
As you said, depending on the expected type you might as well use any other appropriate value. Empty objects or strings are less convential, especially since objects have lots of construction overhead. Do not use them if you don't plan to use (extend) them later.

Is there a way to customize/override assignment operations in JavasScript?

Every time I assign a string, I'd actually like to assign a string object, without the extra code.
This var foo = "bar";
becomes var foo = new String("bar");
Basically hi-jacking the assignment.
Follow-up:
If the above is not possible is there a way to prototype the string variable type, rather than the String object?
As pointed out by armando, the foo would be a string type, but is essentially a customized array. It would be nice to be able to prototype functions to that class.
No this is not possible
If it was possible, you really would not want to do this, at least not globally.
The string variable type does not have all the extra overhead that an object does.
Note: the string array that is created (in your case, foo) would have other properties (eg foo.length)
Objects come at a performance hit
It's not quite what you're looking for, but you may want to look at Overriding assignment operator in JS

Javascript Array Key Retrieval

My JavaScript code stores a lot of data in arrays. I want to retrieve a key using something similar to what I wrote below. It key that should be retrieved is based on variables that are page-dependent . The following code doesn't work. Can anyone give me a solution to this problem?
This is part of a script that does automatic conjugation. (looks for SUBJECT in a div and then looks for VERB in another div and then conjugates the verb by retrieving the conjugated form from the array)
function getarray(Array,Key) {
return Array[Key];
}
Example of how it should work:
verb = innerhtmlfromdiv;
subject = innerhtmlfromotherdiv;
function getarray(Array,Key) {
return Array[Key]; }
conjugatedverb = getarray(verb,subject);
htmltextbox.value = conjugatedverb;
First off, what you want is an Object, not an Array. I'm guessing that you're new to javascript and your previous language was either PHP or PERL, and so you think what you're using is an "Associative Array".
The basics: There is no such thing as Associative arrays in Javascript. There is Objects, and a non-primitive subclass of Object called Array, which has some methods for dealing with Numericly named object properties, and a magic length property.
Since the keys you are dealing with are strings, not numbers, you have no use for Arrays.
Javascript Objects on the other hand are similar to an Associative array in php, or a hash in perl. (but they are not exactly the same thing).
As you have no doubt discovered, with an Object, you can use subscript notation to access certain properties, as in
verbs["go"] = "went";
this is equivilent to
verbs.go = "went";
a common mistake is to think that the dot notation is only used for objects, and the subscript notation for "associative arrays", because this is how it works in PHP. In javascript the two notations are interchangable. Since Arrays are a subclass of Object, the above examples work on them as well (but they don't use any special properties of Arrays).
As for your specific problem:
You need an object full of objects.
so for instance
var verbs = {
"do":{"Truck":"Drive","Blender":"Turn On","Bike":"Ride"},
"take":{"Money":"Steal","Julie":"Accompany","Lever":"Pull}
}
then your function would be:
function conjugate (verb, subject) {
return verbs[verb][subject];
}
and an example of its use would be
conjugate("do","Truck") // returns "Drive"
Try changing the parameter name Array to something else. Array is the name of a built-in function/object in javascript.
I don't quite get the point of the function. This is like writing:
function getValue(var) {return var}
Why not just get the value the normal way without wrapping it in a useless function:
conjugatedverb = verb[subject];
htmltextbox.value = conjugatedverb;
Also, your code doesn't make sense when you claim to do an innerHTML from an element and somehow get an object instead of a string. What is really going on? I think your problem starts even before this snippet of code.

Categories