<body>
<form id="form1" runat="server">
<div id="msg">
</div>
<input id="Button1" type="button" value="HTML Button" />
</form>
<script>
var person = {
firstName: "John",
lastName: "crane",
// 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);
//var obj = document.getElementById("msg");
////obj.innerHTML += this.firstName + " " + this.lastName;
//obj.innerHTML = this.firstName + " " + this.lastName;
////jQuery
////obj.append(this.firstName + " " + this.lastName)
}
}
person.showFullName(); // John crane
//
//The use of this in the global scope
//
var firstName = "Peter",
lastName = "Ally";
function showFullName() {
console.log(this.firstName + " " + this.lastName);
}
this.showFullName(); //Peter Ally
window.showFullName(); //Peter Ally
person.showFullName(); //John crane
//
// If we invoke showFullName with a different object:
//
var anotherPerson = {
firstName: "Runy",
lastName: "when"
}
person.showFullName.apply(anotherPerson); //Runy when
// person.showFullName().apply(anotherPerson); //Error apply not supply
// We have a simple object with a clickHandler method that we want to use when a button on the page is clicked
var user = {
data: [
{ name: "T. Woods", age: 37 },
{ name: "P. Mickelson", age: 43 }
],
clickHandler: function (event) {
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // random number between 0 and 1
// This line is printing a random person's name and age from the data array
console.log(this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object
// And the output will be undefined because there is no data property on the button object
//$("#Button1").click(user.clickHandler); // Cannot read property '0' of undefined
//Fixed
$("#Button1").click(user.clickHandler.bind(user));
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
//
//
</script>
</body>