Meaning of this: methods of objects

for CSCI E3, Harvard University author(s): Larry Bouthillier

by DustyWhite

HTML

<h3>Open your console to see the output</h3>
<p>You can see here, again, that <i>this</i> gets the value of the context from which the function was called.  In this case we've defined a function in the global scope, but we're assigning it to a property of the Person object. </p>
<p>When we make some new Person objects, each one has a reference to the very same sayName() function, but whenever we call that method of the Person the value of <i>this</i> always points to the individual person object we created. </p>

JavaScript

// global function
function sayName(){
    console.log(this);
	console.log("My name is "+this.name);
}

// constructor function in which we assign sayName() to a property
function Person(n){
    this.name = n;
    this.sayIt = sayName;
}

// make some Persons and call sayIt() to see the value of this
var a = new Person("Frodo");
a.sayIt();
var b = new Person("Samwise");
b.sayIt();