<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();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.