Objects and Methods (13-16)


#1

Hi team,

First i will paste two pieces of code and then explain my doubt.

Code1

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(35);

Code 2
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};
rectangle.setHeight(6);

Basically Code1 and Code2 do the same thing. They create a Method that is applied to an Object(bob and rectangle). However, Code1 has an extra piece (bob.setAge = setAge). Why is this needed?

Why is rectangle.setHeight = setHeight NOT needed to make Code2 work?

Thanks so much for taking your time,


16 - What is the point of bob.setAge = setAge?
#2

I m gonna try to explain the best I can

the difference is that in Code1, we create the function as a variable :
var setAge = function (newAge) { //code };
but in Code2, we create the function as a property of rectangle :
rectangle.setHeight = function (newHeight) { //code }
exactly the same why than when we say :
rectangle.width = 4;

so in Code2, after saying
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};

the object rectangle look like this :
rectangle = {
height: 3,
width: 4,
setHeight: function(newHeight) { //code}
}

so you can say : rectangle.setHeight(6);

instead in Code1, after saying
var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;

the object bob looks like this :
bob = {
age: 30
}

so when we say
bob.setAge = setAge;
we are adding the function setAge to the object bob that it can refer the "this" than we are using in the function
property: setAge
value function(age) { //code}


16 - What is the point of bob.setAge = setAge?
#3

make sure you change the setAge to 20 instead of 35


#4

and then change it to 50 on 16