While assigning values in javascript I came across this
var obj = {
resultCodeId: data[i].resultCodes[j].resultCodeId
};
var resultCodeId= data[i].resultCodes[j].resultCodeId;
How do ':' and '=' fundamentally differ in javascript ?Can variable also have properties or just objects in javascript have properties?
=
is for object property or global/local variable assignment.
:
is only for property assignment at object definition.
Also:
You can delete
a property.
You cannot delete
a variable.
var obj = {
p1: 'im p1',
p2: 2
};
obj.p1 = 'im updated p1'; // assign a new value to object property
var v = 'just a var'; // is global outside a function and local inside a function
delete obj.p1; // is ok
delete v; // is not ok
There's a big difference if you use member functions. Local variables are immediately visible, but properties aren't. They require this
. But -- this is the big difference -- sometimes member functions can't see their own properties at all. Some standard code, with a basic constructor:
function Cat() { // constructor with a var and property
var a="local a"; // variable
this.b="local b"; // property
this.showBad = function() { return a+", "+b; } // local a, but searches for b in global
this.showGood = function() { return a+", "+this.b; } // local a and b (but has a bug, explained below)
}
var c1=new Cat(); // using the constructor
var a="GLOBAL A", b="GLOBAL B"; // if we can't see c1's locals, we get these
console.log(c1.showBad()); // local a, GLOBAL B // oops on B
console.log(c1.showGood()); // local a, local b // works fine, using "this"
So far, no big deal. Properties need this
, while variables don't (they actually can't have it). Minor stuff. But this
won't always work. In a javascript member function this
can be anything. If you're accustomed to an OOP language, that seems wrong. Here we call c1.showGood
with this
set to the global scope:
var sGood=c1.showGood; // sGood is the function "c1.showGood"
console.log(sGood()); // local a, GLOBAL B // Argg. this.b didn't work!
That seems fake, but things like that can happen. Because of those two things (vars always work, and we need a reliable way to always see our properties), a standard trick is to lock-down your this
in a variable during construction. It shows the var/property difference nicely:
function Cat() { // constructor with a var and property
var self = this; // self is our permanent, always visible link to this Cat
this.a="local a";
this.b="local b";
this.showGood = function() { return self.a+", "+self.b; }
}
self
is a variable, so our showGood
can always find ours. Meanwhile a
and b
can only be found using a link, which self
accomplishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With