- This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
Viewing 3 posts - 1 through 3 (of 3 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Why = and not : ?
As the title says why do we use = to assign variable a value and not :
Fr instance here, in this function.
Why cannot colon be used instead of equal sign..
packet=new Object();
packet.color=”red”;
packet.type=”plastic”;
packet.size=function(a,b){
return a+b;
}
document.write(packet.size(10,10));
You are venturing into Object Oriented Programming. Read this couple of times before asking anymore question, it’s not that we don’t want to help, it’s because a lot of answers are right there in the text for you.
In short answer to your question.
// Object with literal notation!
obj1 = { name: "Bruce Lee, 1" }
alert(obj1.name); // Bruce Lee, 1
// Object using constructor function!
function Person( name ) {
this.name = name; }
var obj2 = new Person("Bruce Lee, 2");
alert(obj2.name); // Bruce Lee, 2
http://codepen.io/anon/pen/ukiLF
As you can see with one you are defining literal notation and the other has to be instantiated.
Specifically, in this case:
packet=new Object();
packet.color = "red";
You have to use =
because it’s an assignment. packet.color
creates a new property in your object, and = "red"
assigns a value to it. The object itself already exists; you’re adding to it.
In contrast:
packet = {
color: "red"
};
Here, you use :
because you’re using a literal notation—you’re defining the entire object, and its properties, together. color:
is a label for the object property, which is syntactically (if not practically) different, and "red"
is the initial value.