I dont completely understand this piece of code can someone please explain in some sort of detail


#1

// 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;

// make susan here, and first give her an age of 25
var susan = {
age: 25,
setAge: setAge
};
susan.setAge(35);

Thank you if you helped


#2

You simply just need to copy bob's code down and replace the bob with susan


#3

The concept expressed here is that of pointer reference. When we assign a reference to a function to variable, that variable becomes a pointer to the function.

Eg.

function foo() {
    console.log("I am foo!")
}

var bar = foo;

bar(); // I am foo!

Notice that we do not invoke foo() when referring it to bar. We have only copied the function's toString() value, not the outcome of the function.

Now a function written in global window context has window as this, so is not much of value in the global scope. When we refer (assign) the function to an object property, the context shifts to that object.

var bob = {};
bob.setAge = setAge;
bob.setAge(25);
console.log(bob.age); // 25

The same will apply to susan

var susan = {
    setAge: setAge
};
susan.setAge(30);
console.log(susan.age); // 30

Starting to make sense?