In C++ I have learned that Variables are the used for Data Storage and Objects are the instance of a Class. But in JavaScript I have seen people referring variables as an Object. Why are the Variables referred as Objects in JavaScript. I am getting confused with that.
In javascript, a variable can either hold a single piece of data itself (like the number 3 or a text string like "Having Fun") or it can hold a reference to an entity like an array or an object.
An object in javascript is essentially a container in javascript. It can hold multiple properties that are each accessed with a key. For example, an object could have a property named "name" that contains the value "Bob", it could also contain a property named "Age" with a value of 29. Objects can have as many properties as one wants. As such objects are essentially a collection of multiple variables, where each variable has its own name and value.
There are technically no "classes" in javascript so it doesn't work the same way that C++ does. Javascript uses prototypes and objects instead of classes and instances in C++.
In reference to the specifics of your question, a variable can contain a value or a reference to an object. There is no right or wrong, it depends upon the problem to be solved.
Some examples:
var person = {}; // a variable `person` that contains a reference to an empty object
person.name = "Bob"; // add a property "name" and value to the object
person.age = 29; // add a property "age" and value to the object
var numPeople = 12; // a variable that just contains a number
Javascript is prototype based OOP language.
Prototype-based programming is a style of object-oriented programming
in which classes are not present, and behavior reuse (known as
inheritance in class-based languages) is performed via a process of
cloning existing objects that serve as prototypes.
In Javascript we use DOcument Object Model(DOM) for refering to different elements of web page.
so when we refer to window,document,form they all are objects and variables are declared like
var x=0;
following will be example of object assignment.
var w=window;
Related
Attempting to assign a scope object to a JavaScript variable to do minor manipulation before sending to my API. However, any changes made to the JavaScript variable change the scope object.
var recruitingCallListOutput = $scope.RecrutingCallingList.Recruit;
// manipulation of recruitingCallListOutput
The manipulation actually still updates the scope object which is not desired. Feel I am not understanding something in AngularJS correctly. Is there a way to grab the data and detach it from the scope?
In your example, recruitingCallListOutput is a reference to $scope.RecrutingCallingList.Recruit (see https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 for more detail.) You will want to make a copy of $scope.RecrutingCallingList.Recruit.
If Recruit is a shallow object, meaning no nested objects (property values are primitives only), you can simply do
var recruitingCallListOutput = Object.assign({}, $scope.RecrutingCallingList.Recruit);
If you have nested objects/arrays as property values, you'll need to deep copy. It's been a while since I have been in the angular world, but
var recruitingCallListOutput = angular.copy($scope.RecrutingCallingList.Recruit)
you could actually use angular.copy in both examples.
This is nothing to do with AngularJS. It's Javascript, and it's expected behaviour.
For example, if you open the browser console (F12->Console) right now and run this:
var foo = {x:1};
var copy=foo;
copy.x=2;
console.log(foo.x);
you will see {x:2} printed out.
This is the same behaviour you would expected for any object reference in Javascript, C#, Java, etc. Because you are making a reference and not a copy, any changes to the reference are actually changes to the original.
The simplest way to solve this problem in your case is to copy the values you are interested in from the item in question into a totally separate object and modify that copy.
e.g.
var recruitingCallListOutput = {
name: $scope.RecrutingCallingList.Recruit.name,
age:$scope.RecrutingCallingList.Recruit.age,
modifiedSomething: $scope.RecrutingCallingList.Recruit.something + 42 //or whatever modifications you need to make
...and so on.
};
There are ways to "clone" an object in Javascript but unless your object is really really complex I would be careful. And consider if you really need all of the properties of the original object anyway, perhaps you only need to send some of them to your backend.
I am reading about getters and setters in javascript. I would like to know if there is a difference between this two ways of coding with and without setters
first way, without setters.
>obj1 = {
arr: [];
}
>obj1.arr.push('first')
>obj1.arr
[ 'first' ]
Second way, with setters.
>obj2 = {
set add(data) {
this.arr.push(data);
},
arr: []
}
>obj2.add = 'first'
>obj2.arr
[ 'first' ]
The setter syntax in your example does not really prevent the client code to still add a value using the direct push call as in the first code block. So the difference is that you just added another way to do the same thing.
To make a fair comparison, you would have to define the same method in both alternatives: once as a normal method and once as a setter method, and then the difference is just the syntax how the argument is passed to the method, either with obj.add('first') or obj.add = 'first'.
In this actual case I would vote against the setter, because it gives the false impression that if you "assign" another value, the first assigned value is overwritten:
obj.add = 'first';
obj.add = 'second';
... but obviously this is not the case: both values exist in the object now.
First, The set Syntax bind an object property to a defined function. In this particular example, there is no difference between two codes, but let's say for example you want to check if the value is negative before adding it to the array, so you can use set to Encapsulate that behavior.
So basically, using setter is only to add additional encapsulated behavior to the functions of the objects.
The way of accessing the array index called bracket notation. it is equal to dot notation, except the bracket notation allows you to set new properties to objects or arrays dynamically.
Hope this help you.
I think difference only about "how it looks like". Using setters it's closest way for understanding for people who came to js from object oriented languages.
The getter/setter property is not the same as "normal" instance property, one is called "named data property", the other is called "named accessor property".
Please let met quote below part of documents from the ECMAScript 5.1.
https://www.ecma-international.org/ecma-262/5.1/#sec-8.10.1
An Object is a collection of properties. Each property is either a
named data property, a named accessor property, or an internal
property:
A named data property associates a name with an ECMAScript language
value and a set of Boolean attributes.
A named accessor property associates a name with one or two accessor
functions, and a set of Boolean attributes. The accessor functions are
used to store or retrieve an ECMAScript language value that is
associated with the property.
An internal property has no name and is not directly accessible via
ECMAScript language operators. Internal properties exist purely for
specification purposes.
There are two kinds of access for named (non-internal) properties: get
and put, corresponding to retrieval and assignment, respectively.
And
If the value of an attribute is not explicitly specified by this
specification for a named property, the default value defined in Table
7 is used.
Javascript objects use a key value system (like a hash, map, or dictionary in other programming languages). The key is referred to as a property and within an object is written like this:
var object = { property01: value01, property02: value02 }
Within objects we can access the value of the property using two access methods.
object.property01
object['property01']
In the example above property01 and property02:
What is the type of the variable holding the property name, and how is it stored in memory?
I'm not sure if I understand your question correctly, but the closest answer I could reference is this:
Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
It's a variable, but instead of being attached to the window object, it's attached to another variable.
Was reading this
https://github.com/angular/angular.js/wiki/Understanding-Scopes
and there is same thing on stack overflow:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
Here is the thing which I do not understand:
Suppose we then do this:
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name.
Suppose we then do this:
childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope.
So in the object array example - parent scope is updated because the objects (anArray and anObject) are not found in the childScope
But in the first example its the same. Except that it is the string. It is not found in the child scope, so should be updated in parent scope. Why it is not updated in parent scope?
Or why array and object in 2nd example are not created in child scope?
Hope its ok to create new thread based on original thread, because just for comment it is long text and would not be easy to read.
In a sense, all three of those examples are really the same. In the second two examples, there's simply an extra object-to-object "hop". The first one:
childScope.aString = "child string";
There's just one object involved: the "childScope" object. (By the way, the word "scope" here makes me uneasy, but let's move on.)
The second pair of examples involve two objects:
childScope.anArray[1] = "22";
childScope.anObject.property1 = 'child prop1';
The two objects in the first of those two statements is the "childScope" object, and then the "anArray" property of the "childScope" object. Presumably, if the statement doesn't cause an error then the value of that property is an array. I stress value because that's the key difference between this reference to a property of "childScope" and the first example ("aString") - here, we want the value of the property because it must be used for the subsequent reference. In the first "aString" example, the statement was setting the value, so there was no interrogation of the current value.
Once the value of childScope.anArray has been fetched, then that object reference is in turn used in a property reference expression. Here, as in the first "aString" example, we're setting the value of the "1" property of the "anArray" object. That's pretty much exactly the same operation as in the "aString" example. (The "anObject" example is much the same.)
When setting a property value (or an array element value; that's really the same thing), JavaScript does not look for a property up the prototype chain. When using the value of a property, it does. An interesting effect of that is this. In the first "aString" example, if there were an "aString" property on the prototype, then once that property is set on the instance ("childScope"), then the prototype property is effectively hidden from view as far as that instance object is concerned.
I have a variable called jsonAllSignOffs that is created by a .NET JSON service and sent to the client. It is essentially a struct containing various arrays. The values of these arrays are arranged such that if you took the nth element of each array, all together that would be the collected properties of the nth Sign Off. Obviously a list of Sign Off objects containing these properties would be better, but unfortunately this is a legacy application and changing it's architecture in this manner is out of scope.
What I'm trying to do is create a variable called jsonUserSignOffs that is essentially a subset of jsonAllSignOffs with all the same properties. However jsonAllSignOffs is not a type that I can instantiate. I figured declaring a variable and assuming the properties by assigning into them would "build" the object, but apparently that's not the case.
var jsonUserSignOffs;
jsonUserSignOffs.isAuthor = jsonAllSignOffs.isAuthor; //error jsonUserSignOffs is undefined
Since javascript doesn't support classes and is pretty lax with variables I figured the only way to create a struct like jsonAllSignOffs was to declare the variable and assign values to it's properties. I know these properties are not defined anywhere, but I thought assigning values to them would instantiate them at the same time. I come from a C# background where I would use a class. Javascript is less familiar to me, and I'm unclear on how to proceed.
Try this
var jsonUserSignOffs = {}; //creates an empty object using object literal notation
jsonUserSignOffs.isAuthor = jsonAllSignOffs.isAuthor;
OR:
var jsonUserSignOffs = {
isAuthor: jsonAllSignOffs.isAuthor
};