console.log(school.hasOwnProperty ("schoolName")); // true because schoolName is an own property on the school object
// Prints false because the school object inherited the toString method from Object.prototype, therefore toString is not an own property of the school object.
console.log(school.hasOwnProperty ("toString"));
var person = {
firstName: "Penelope",
lastName: "Barrymore",
fullName: function () {
// Notice "this" refers to an object
console.log(this.firstName + " " + this.lastName);
// We could have also written this:
console.log(person.firstName + " " + person.lastName);
}
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
// Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,
// "this" will have the value of the person object because the person object will invoke showFullName ()
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
}
person.showFullName (); // Penelope Barrymore
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will have the value of the global variables
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
console.log (this.firstName + " " + this.lastName);
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
}
}
showFullName (); // Peter Ally
person.showFullName() // Penelope Barrymore
// window is the object that all global variables and functions are defined on, hence:
window.showFullName (); // Peter Ally
// "this" inside the showFullName () method that is defined inside the person object still refers to the person object, hence:
person.showFullName (); // Penelope Barrymore
In a method, this refers to the owner object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), and apply() can refer this to any object.
fullName : function() {
return this.firstName + " " + this.lastName;
}
In an object method, this refers to the "owner" of the method.
The person object is the owner of the fullName method.
[object Window]:
var x = this;
x // [object Window]
function myFunction() {
return this;
}